Thursday, March 17, 2016

Properties in C#

In today's blog post, I will be discussing the properties in C#. We will see how properties are useful and are a great time saving feature for us.

Properties in C#

Properties are simply like the getters and setters methods which allow us to control the value being set/ read of a private variable in a class. They let you access the property as if it was a field but in reality they are special methods called accessors.

Properties in C#


In order to better understand their importance, let's look at the way we would have written some code if properties hadn't existed.


public class Employee 
{       private int employeeId;        public int GetEmployeeId()        {              return employeeId;        }        public void SetEmployeeID(int id)        {              employeeId = id;        }  }
If we had multiple properties, imagine how the lines of code would have grown.

Since properties exist, we can write it like this:

public class Employee 
{       private int employeeId;      public int EmloyeeId      {            get            {                  return employeeId;           }
          set            {                   employeeId = value;            }
      }  }


And since our accessors do not require any special logic for get and set, we can use auto-implemented properties like this:


public class Employee 
{            public int EmployeeId  {get; set;}  }

So all that lines of code are replaced by only one line as seen. This is so helpful to the developers and we use it all the time without even giving it much thought that how our task is made so much easier by the properties.

So there are two accessors: get and set. As expected, get is used to read the value of a variable and set is used to write the value. Both get and set can have different accessibility levels. If the property has only get accessor then it's a read-only property.
In the case of auto implemented properties, compiler creates a private and anonymous backing field that can be accessed only through property's get and set accessor.

Another thing worth mentioning is that from C# 6 onwards, auto-implemented properties can also have default values. Earlier, if we needed a default value, we had to manually write the code for properties accessors. But now it can be done like this:

public class Employee 
{ 
     public int EmployeeId {get; set;} = 1; 
}


So, here the default value is 1.

Conclusion

Properties help us developers to write our code quickly and efficiently. We should take full advantage of the properties instead of manually writing old style way of getters and setters. And we should thank the compiler for generating so much code for us when we use auto-implemented properties ;)

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


No comments:

Post a Comment