Why use simple properties instead of fields in C#? [duplicate]

Using properties has a couple of distinct advantages:

  • It allows for versioning if later you need extra logic. Adding logic to the getter or setter won’t break existing code.
  • It allows data binding to work properly (most data binding frameworks don’t work with fields).

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…

Leave a Comment