If you are a beginner, you might get confused between a field and a property. You can store value using either a field or a property and retrieve the value back. You can even protect both fields and properties using access modifiers such as private or protected. So you might wonder, why we need to have property when you can achieve the same using field or vice-versa.
What is a Field?
Fields are actual variables in your object that stores a particular piece of information. Let us discuss the same with the help of the code. Below ‘Employee’ class has 3 fields for storing Name, Id, Salary respectively.
You can create instance of the class and store value in the field using that object, as shown below
Employee e1 = new Employee();
e1.firstName = "Mugil";
What is a Property?
Properties offer another level of abstraction to expose the fields. Let’s create a property ‘Name’ which would combine firstName and lastName and display the complete name.
public string Name{
get {
return firstName + " " + lastName;
}
}
Employee e1 = new Employee();
e1.firstName = "Mugil";
e1.lastName = "Ragu";
Console.WriteLine(e1.Name); // Will print "Mugil Ragu"
Please note that we have only exposed ‘get’ and have never used set. This restricts the developer in setting the value for the property ‘Name’. If you try to set the value to this property, you’ll get compile time error.
This additional abstraction layer in properties enables the developers to apply access modifiers separately for getters and setters. In the above case, we have only getters and no setters. In some cases, you can have private setters and public getters – so that you can allow external classes/components to get the value of the property but could not set the value.
In the above example, we have implemented properties for the fields that we have defined in the class. But there is a concept of auto-implemented properties. Let’s see an example.
public string Department { get; set; }
Above statement is an example of auto –implemented property. Whenever compiler sees an auto implement property, it creates a private backing field and it automatically implements the property for the same.
In this case, C# compiler will generate code something like below
private string _Department;
public string GetDepartment()
{
return _Department;
}
public void SetDepartment(string value)
{
this._Department = value;
}
Please note that the name of the private backing field and method names for getting and setting the value would be different as it is compiler generated. I’ve just came up with these method names for ease of understanding.
So, whatever the auto – properties that you use, the compiler will generate a backing fields and associated methods to access the fields for you. To put it in a nutshell, fields are direct variables in your object whereas properties offer abstraction and sit at another layer on top of the ‘fields’ layer.
Let me know your thoughts in the comments section