Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use public properties for private fields in C#? [closed]

Tags:

c#

properties

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?

like image 567
Nishant Kumar Avatar asked Aug 27 '10 05:08

Nishant Kumar


2 Answers

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.

like image 108
Timwi Avatar answered Sep 17 '22 20:09

Timwi


Because you can validate the specified value in a property.

like image 21
jgauffin Avatar answered Sep 18 '22 20:09

jgauffin