When to use get; set; in c#
I'm failing to understand what the difference is between initializing a variable, getting its value like this:
//define a local variable.
int i;
i= 0;
Console.WriteLine(i);
and the get; set开发者_JS百科; usage:
public int i
{
get;
set;
}
i = 0;
Console.WriteLine(i);
I've read some articles, but don't understand when I would use it.
Basically, in that case, there is no difference, of the (many) advantages of using a property is the ability to add Events to your property, like so:
public delegate void ChangedEventHandler(object sender, EventArgs e);
int m_i = 0;
public int i
{
get { return m_i; }
set { m_i = value; iChanged(self, null); }
}
public ChangedEventHandler iChanged;
This allows for code to know when I has been changed (there might be some syntax errors, I haven't focused on C# in a while, but the idea is similar). This is extremely important in winforms, as this is the major way of knowing when a button (or similar) has been clicked.
Also, this allows for additional functionality in the setter of a property, e.g. checking if it is in a certain range, like this:
int m_i = 0;
public int i {
get { return m_i; }
set { if (value > 10) throw new Exception("I cannot be greater than 10!"); m_i = value; }
}
If you think you might need a more complicated getter or setter later, the automatic property syntax lets you upgrade without recompiling all callers. Moving from a field (member variable) to a property is a breaking change, however.
Eric Lippert addresses the topic. Twice.
Basically, it adds overhead in exchange for the ability to attach an event. Apart from that, it adds complexity and verbosity, which makes code more difficult to read. If you need to add validation handlers, it is a neat way to do it. In some cases. In most cases, you know (and want to know) exactly where a variable (member) is being modified. If you don't, then you have a code management problem, not a language issue.
The idea that everything "object oriented" is better, is false. Most developers are coming to understand that. I've been doing this work for 30 years, and I can tell you that 98 times out of 100 - simple is better. Spend your coding effort on efficient algorithms that don't add unnecessary complexity, and you will go far and survive trends.
Lets forget properties for a second... The real question you're asking (and you might not even know it) is why do you need properties (or getters and setters in some other languages) in the first place?
It's to promote encapsulation.
Properties just offer a nicer syntax for getters and setters, aka accessors (and indeed, a property just wraps set() and get() methods under the hood).
In c# 3 the c# team came up with auto properties, because the vast number of properties don't do anything with the variables (no additional logic), so auto properties are short hand for that scenario.
The syntax you are describing is known as an auto property.
Before the syntax was introduced in .NET 2.0, we created a property like so:
int _myVar;
int MyVar
{
get { return _myVar; }
set { _myVar = value; }
}
.NET 2.0 introduced the shorthand syntax, allowing the compiler to automatically create the backing variable (_myVar
in my example above)
int MyVar
{
get;
set;
}
The key difference between setting a variable and a property such as this is that we can control the getting and setting of the property (read only properties, or a function call whenever a value is set to the property, for example.)
public int i {get ; set;}
creates auto property i
of type int
which is short for
private int _i;
public int i
{
get{ return _i;}
set{ _i = i}
}
The part confusing me was the terms accessor
, mutator
and property
, along with the { get; set; }
, as though it's some magical improvement alias over just making the field public
.
- accessor = method to access a
private
field (in C#, both getter/setter) - mutator = method to change a
private
field (just a setter) - property = same as an
accessor
in C#.
Purely as:
private int myNumber;
public int MyNumber { get; set; }
they are totally useless, serving as noise code version for:
public int myNumber;
If, however you add some checks like so:
private int myNumber;
public int MyNumber
{
get
{
return myNumber;
}
set
{
if (myNumber < 0)
throw new ArgumentOutOfRangeException;
myNumber = value;
}
}
..then they do actually serve the regular used-to getter/setter purpose.
It is basically concept of Object Oriented Programming.
when you use int i; ( This consider as field and this field can be internal usage as well as it can be use from outside current class depending upon access modifier. (Public , Private , Protected)
Now when you use get; set; it is property of class. It can also set from other class but diffrence it is access like method and it provide other functionality like notification of property change and all that.
Use filed when you don't want any control over it but if you want to control then use property. Also you can have get and set with public , private and protected which can also provide more flexibility interm of encaptulation.
It is one concept of OOPs.
There are two main advantages using the Get\Set Property :
- Without affecting base class value, we can change the variable value in derived class using the get and set method.
Eg :
class User
{
private string name = "Suresh Dasari";
public string Name
{
get
{
return name.ToUpper();
}
set
{
if (value == "Suresh")
name = value;
}
}
}
- Also, we can able to validate\Restriction\Raise the Events, in values set property section.
精彩评论