Properties vs Fields in C#

One of the most asked question is the difference between Properties and Fields in C#. Also, we should understand the situation where to use a Property or a Field.

Fields: A field is simply a variable of any type that is declared directly in a class or struct.

Properties: Properties expose fields. A property provides a flexible mechanism to read, write, or compute the value of a private field. Properties can have validations.

When to use

Fields:  Fields should generally be used for variables that have private or protected accessibility.

Properties: Properties can be used as if they are public data members. Data that your class exposes to client code should be provided through methods, properties or indexers. Properties are actually special methods called “accessors” and it provides abstraction by hiding the implementation.

Difference

  1. Interfaces can have properties but not fields. As Interface members are always public hence properties are supported by the interface.
  2. Properties can have validations. Properties have set method where we can put validations before assigning the value.
  3. Properties can have only get accessor or can mark setter as private to make it Read-Only for the client whereas Fields do not have such feature.
  4. Properties provide granular control to the developer whereas fields are pretty basic.

Auto-implemented properties

In order to simplify the property declaration C# 3.0 provided Auto-implemented properties which do not require additional logic in property accessor. Developer is not required to declare a backing field. Though, backing field is auto generated by compiler but for the developer code is more concise and readable.