Possible Duplicates:
Should I use public properties and private fields or public fields for data?
Difference between Automatic Properties and public field in C# 3.0
People seem to dogmatically insist on the use of public properties over fields but why is it so ultra-important in the case of simple properties?
How is
public int Foo { get; set; }
so incredibly different than
public int Foo;
?
Off the top of my head I can think of few practical differences between the two:
Other than these fairly rare cases, changing Foo to be a computed property later results in 0 lines of code changed.
Properties can be used to read only or write only other fields. This could be done by declaring only either get{} or set{}. Also they can have access modifiers, like private, so you can only get or set their values inside their class.
You want to use properties over fields becuase, when you use properties you can use events with them, so in a case when you want to do some action when a property changes, you can bind some handlers to PropertyChanging or PropertyChanged events. In case of fields this is not possible.
Property always a better choice instead of public variables. Property is safe while public variables are unsafe. And you can not debug with public variables but you can do that with property. Public variables are useful.
A field is a variable of any type that is declared directly in a class. A property is a member that provides a flexible mechanism to read, write or compute the value of a private field. A field can be used to explain the characteristics of an object or a class.
Using properties has a couple of distinct advantages:
In addition, there are almost no disadvantages. Simple, automatic properties like this get inlined by the JIT compiler, so there is no reason not to use them.
Also, you mentioned:
Other than these fairly rare cases, changing Foo to be a computed property later results in 0 lines of code changed.
This doesn't require your code to be changed, but it does force you to recompile all of your code. Changing from a field to a property is a breaking API change which will require any assembly which references your assembly to be recompiled. By making it an automatic property, you can just ship a new binary, and maintain API compatibility. This is the "versioning" advantage I mentioned above...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With