+ 1
How to use the get and set property in C#?
Currently I have been learning c# too in SoloLearn..here they were explained above c# accessors properties..but I can't understand that. could anyone explain me clearly?
2 Réponses
+ 3
Properties are there to hide the implementing variable from other classes. Generally you will just use the auto properties. Auto properties generate their own backing variables.
public int Prop1 { get; set; }
public int Prop2 { get; protected set; }
You can now use the above properties as they are.
myObj.Prop1 = 2;
int test = myObj.Prop2;
If later on you need to calculate the value or perform some action you don't have to change the public interface and break anything that uses it. The setter automatically declares a variable called value to use when setting your own backing variables.
private int _prop1;
public int Prop1
{
get
{
return _prop1;
}
set
{
if (value != _prop1)
{
OnProp1Changed();
_prop1 = value;
}
}
}
0
Thank you all