+ 1

C# question for properties/get/set

my question is why do we have to use a property and use the get and set in order to extract and set the value from the private field. Why dont we use a simple public variable?

1st Aug 2017, 5:38 PM
Rod Natal
Rod Natal - avatar
2 Answers
+ 2
just in case you want more control over your private variables. Also you can do get private set which is what I mostly use it for.
1st Aug 2017, 5:41 PM
Jordan Chapman
Jordan Chapman - avatar
+ 1
In the beginning public fields a are fine. If the code is just for our self and does not contain a lot of classes. But soon you will discover that to you want to check if the data is valid before it is set. (encapsulation) Using properties gives you the possibility to change your validation methods without recoding the application because you can change the class and you know where the validation methods are. (maintainance) There is a very good example by microsoft about a bankaccount. Using AccountBalance as a public field. Is this a good idea. No your are not allowed to set just anything to the AccountBalance field. So you need methods that check whether you are allowed to set the value you want to set. It is a good habit to use a default property instead of a public field, you'll benefit later from it. public int AccountBalance; public int AccountBalance {get; set;}
1st Aug 2017, 8:28 PM
sneeze
sneeze - avatar