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.
1 2 3 4 5 | public class Employee { private int _id; private string _name; } |
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.
1 2 3 4 5 6 7 8 9 10 | public class Employee { private string _name; public string Name { get { return _name; } set { _name = value; } } } |
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
- Interfaces can have properties but not fields. As Interface members are always public hence properties are supported by the interface.
- Properties can have validations. Properties have set method where we can put validations before assigning the value.
- 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.
- Properties provide granular control to the developer whereas fields are pretty basic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | private int _marks; public int Marks { get { return _marks; } set { //validation if (value > 100) throw new ArgumentOutOfRangeException("marks cannot be greater than 100"); if (value < 0) throw new Exception("invalid value"); _marks = value; } } public int Marks { get { return _marks; } private set //set is private { _marks = value; } } //Read-only property without set public int Marks { get { return _marks; } } |
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.
1 2 3 | public int Marks { get; set; } public int Marks2 { get; private set; } |