Understanding Use Of Properties In C# With Example

A property is a member that provides a way to read, write, and manipulate the value of a private field. Properties can be used as if they are public data members, but internally they are special methods called accessors (get, set). We can say properties are syntactic sugar on getter and setter methods which can be used to set or get private fields. Properties are helpful to achieve the encapsulation feature of object-oriented programming.

Why do we need properties?

I will try to explain this with an example.

Brief information about the below program
  • I created one Class "Employee" and added three fields _firstName, _lastName, _salary.
  • Inside the main method I created an object of "Employee" class and assigned values for three fields.
  1. namespace PropertiesDeepDive
  2. {  
  3.     static class Program  
  4.     {  
  5.         private static void Main()  
  6.         {  
  7.             Employee emp = new Employee();  
  8.             emp._firstName = "John";  
  9.             emp._lastName = null;  
  10.             emp._salary = -1000;  
  11.             Console.WriteLine("FirstName:{0}\nLastName: {1} \nSalary: {2}", emp._firstName,emp._lastName, emp._salary);  
  12.             Console.ReadLine();  
  13.         }  
  14.     }  
  15.     public class Employee  
  16.     {  
  17.         public string _firstName;  
  18.         public string _lastName;  
  19.         public int _salary;  
  20.     } 
  21. }
Below points clarify what's wrong with the above program:
  1.  The very first thing wrong about this program is it is violating Encapsulation principle of OOPS as it is exposing internal details of class to the outside world by making fields public.

  2. The second problem is, in the real world the last name cannot be null or Salary cannot be negative,  but in the above program, we can set _lastName to Null and _salary to negative value thus corrupting object of Employee. Also, we cannot restrict the user from assigning the negative value to _salary or Null value to _lastName to solve these issue C# comes up with Properties member.
Syntax  For Property
  1. <Access-Modifier> <Type> <PropertyName> {        
  2.   <Access-Modifier> get {        
  3.        /*Get Accesser Logic*/        
  4.   }        
  5.   <Access-Modifier> set {        
  6.       /*Set Accesser Logic*/        
  7.   }        
  8. }      
  9. /*Example of property*/      
  10.  public int Salary    
  11.  {    
  12.    get    
  13.    {    
  14.      return _salary;    
  15.    }    
  16.    set    
  17.    {    
  18.      _salary = value;    
  19.    }    
  20.  }    
Property Sytax Explanation
  • <Access-Modifier>
    Can be Public, Protect, Private which decides accessibility.

  • <Type>
    Can be the value type or reference type (eg Class, Interface, struct or any value types like int)

  • <PropertyName>
    It is the name of the property

  • get
    This is called a get accesser and is used to get the value

  • set
    This is known as a set accesser and is used to set the value
Employee class is modified to solve issues that appeared in the first program as below,
  • Changed _firstName, _lastName, _salary fields from the public to private.
  • Added three public properties FirstName, LastName and Salary for _firstName, _lastName, _salary fields respectively.
  • For FirstName and LastName property Inside set accessor, the check for value is Null and if the value is Null it will throw an exception
  • Also added a check for Salary that if the value is less than or equal to zero  itthrows an exception that salary cannot be negative
  • In the Main class two objects of Employee class emp1 and emp2, for emp1 are assigned correct values for all three fields and in emp2 assigned Null for Lastname and Salary is in the negative
  1. namespace PropertiesDeepDive    
  2. {    
  3.     static class Program    
  4.     {    
  5.         private static void Main()    
  6.         {    
  7.             Employee emp1 = new Employee();   
  8.             emp1.FirstName = "John";    
  9.             emp1.LastName = "Mehar";    
  10.             emp1.Salary = 1000;    
  11.             Console.WriteLine("FirstName:{0}\nLastName: {1} \nSalary: {2}",    
  12.                 emp1.FirstName, emp1.LastName, emp1.Salary);  
  13.   
  14.             Employee emp2 = new Employee();   
  15.             emp2.FirstName = "John";    
  16.             emp2.LastName = null;    
  17.             emp2.Salary = -1000;    
  18.             Console.WriteLine("FirstName:{0}\nLastName: {1} \nSalary: {2}",    
  19.                 emp2.FirstName, emp2.LastName, emp2.Salary);  
  20.   
  21.    
  22.             Console.ReadLine();    
  23.         }    
  24.     }    
  25.     public class Employee    
  26.     {    
  27.         private string _firstName;    
  28.         private string _lastName;    
  29.         private int _salary;    
  30.     
  31.         public int Salary    
  32.         {    
  33.             get    
  34.             {    
  35.                 return _salary;    
  36.             }    
  37.             set    
  38.             {    
  39.                 if (value < 0)    
  40.                     throw new Exception("Salary can not be negative");    
  41.                 _salary = value;    
  42.             }    
  43.         }    
  44.     
  45.         public string FirstName    
  46.         {    
  47.             get    
  48.             {    
  49.                 return _firstName;    
  50.             }    
  51.             set    
  52.             {    
  53.                 if (value == null)    
  54.                     throw new Exception("FirstName can not be Null");    
  55.                 _firstName = value;    
  56.             }    
  57.         }    
  58.     
  59.         public string LastName    
  60.         {    
  61.             get    
  62.             {    
  63.                 return _lastName;    
  64.             }    
  65.             set    
  66.             {    
  67.                 if (value == null)    
  68.                     throw new Exception("LastName can not be Null");    
  69.                 _lastName = value;    
  70.             }    
  71.         }    
  72.     }    
  73. }   
Output of the above program,
 
 

Program has worked fine for first Employee object i.e emp1 as every field was valid, but in case of emp2 it throws an Exception as LastName is Null as inside LastName property we have written logic to throw an exception if LastName is Null.
 
What problems does the above program solve?
  1. As _firstName, _lastName, _salary are private it solves the problem of exposing implementation details of class to outside world and hence achieving encapsulation principle.

  2. Also _firstName, _lastName cannot be set to Null as inside set accessor checked if the value is Null and _salary also cannot be set to minus. Thus we are saving our object from getting corrupted due to invalid data.