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:
- Accessing the member using reflection (rare, and most decent reflective algorithms will account for the difference)
- The second entry allows you to use the field as a valid parameter for ref and out parameters, which would seem to be an advantage to using the field version
- Fields don’t work in Remoting (probably, I’ve never used remoting but I imagine they wouldn’t)?
Other than these fairly rare cases, changing Foo to be a computed property later results in 0 lines of code changed.
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:
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…