+ 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?

6th Mar 2018, 5:46 AM
Thiru Arasu
Thiru Arasu - avatar
2 Respuestas
+ 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; } } }
6th Mar 2018, 6:09 AM
Jesse Bayliss
Jesse Bayliss - avatar
0
Thank you all
6th Mar 2018, 8:26 AM
Thiru Arasu
Thiru Arasu - avatar