If I make a class member private, and then I want to acess that member, we have to define a public property for that member. But then I wonder: If we can use the class member publicly by declaring a public property for it, then why don’t we just define the class member itself as public?
Property accessors (get, set methods) allow you to change your implementation is future. For example, you may start with a backing field (private class member) but later the property may become a result of some calculation. Further, property syntax allows you to have read-only members - so you can change the value only inside your class, outside world can only read it.
Microsoft recommends the use of public properties in place of public fields for reasons of binary compatibility. This is only an issue if you are writing a library (which other programs will access).
Basically, imagine this scenario:
- You create a library with a public field
- Someone else writes a program that uses your library and accesses that public field
- Now you want to change your field to a public property because you need to validate the input value, or the property has become the result of a calculation, or you want it to throw exceptions because it’s obsolete, or whatever.
- The user tries to upgrade your library, but not the program that uses the library.
This will completely break the program — it will stop working and only crash. However, if instead of the field you had a public property right from the start, then you could swap the library.
This is, of course, only relevant for libraries. In all other cases, the advice is not really relevant and you can use fields if you like. If you later find that you needed a property, you can still change it to a property then and your program will still compile fine.
Here are some reasons of why we use public properties instead of public fields.
- You can write more complex codes in get/set methods, while there is only a single value in fields.
- Properties makes your code more "OO". Say a class called Person, we can easily guess that there is a property called "Name" in it. But a public field named "Name" is really weird.
- Some attributes work for properties only(AttributeTargets.Property).
The reason for using properties is very simple. You can always change the code handling getting/setting it's value without breaking any external program depending on your work - this is not possible with fields. Furthermore, properties can be marked as virtual, and thus, can be redefined by child classes - again without breaking any compatibility.