Properties vs Fields

There has been a lot of discussion around this topic and I only recently caught up and found some interesting gems from a variety of locations. Jon Skeet’s article Why Properties Matter is a good starting point. Robert Paulson also has a comprehensive list of pros. To summarize the pros and cons:

  1. Properties allow access modifiers on getters and setters
    public string Name { get; private set; }

    which makes the property read only publicly but read/write privately.

  2. Properties can be virtual. Fields cannot be overwritten.
  3. Properties can be declared in an interface. Fields cannot.
  4. Properties provide fine-grained control such as data validation or simultaneously logging to a file.
  5. .NET (by design) uses properties for data-binding making them necessary.
  6. Changing a field to a property (or vice-versa) breaks binary compatibility, thus it’s a breaking change (requires recompilation). It may be desirable to use properties for future extensibility instead of thinking YAGNI.
  7. Moving from fields to properties breaks source compatibility. For example, if you are using reflection on any of the fields which have since been changed to properties, then the code for reflection will need to be updated (PropertyInfo vs FieldInfo). Similarly, serialization will also break.
  8. Since properties can contain some additional logic, they can throw arbitrary exceptions. Fields cannot.
  9. Break points can be set on properties making them easier to debug. They can’t be set on fields.
  10. Fields can be used for ref or out arguments but properties can’t.
  11. Properties can do lazy loading
    public string Name {
        get {
            if (this._name = null) LoadName();
            return this._name;
        }
    }
    

These reasons should be good enough to persuade you to use properties instead of fields.

Comments

Post is no longer open for comments.