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=
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 :
Eg :
class User
{
private string name = "Suresh Dasari";
public string Name
{
get
{
return name.ToUpper();
}
set
{
if (value == "Suresh")
name = value;
}
}
}
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
.
private
field (in C#, both getter/setter)private
field (just a setter)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.