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:
- 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.
- Properties can be virtual. Fields cannot be overwritten.
- Properties can be declared in an interface. Fields cannot.
- Properties provide fine-grained control such as data validation or simultaneously logging to a file.
- .NET (by design) uses properties for data-binding making them necessary.
- 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.
- 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.
- Since properties can contain some additional logic, they can throw arbitrary exceptions. Fields cannot.
- Break points can be set on properties making them easier to debug. They can’t be set on fields.
- Fields can be used for
ref
orout
arguments but properties can’t. - 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.