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

Solution 1:

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...

Solution 2:

One good reason is that you can vary the get/set accessibility.

public int Foo {get; protected set;}

Solution 3:

A property is a language element which logically represents a property of the thing being modeled by the class. The class Car models a car; colour is a property of cars; therefore, Color is a property of Car.

A field is an language element which represents an implementation detail of the class. Your car does not have a "colour field", so your program's representation of a car should not expose a field called Color. It might contain a private implementation detail whereby the property Color is implemented by a field, but that's a private implementation detail, not a publically accessible part of the model.