Immutable Object In C#


Immutable objects are those objects in which once data has been loaded, it cannot be modified any way, internally or externally.

What kind of scenario immutable objects are prepared to use

An immutable object is used where ever data is static. For example, when master data is loaded into memory we don’t want to change it. For example, currency master, state master, etc. 
 In order to make a class immutable, it is a 3-step process.
Data should not be changed externally, so remove the setter in the class.
  1. Class state   
  2. {  
  3.    private string _statename;  
  4.   Public string statename   
  5. {  
  6.   Get {return _statename;}  
  7.   Set{_ statename =value }// step 1 remove the setters.  
  8. }  
  9. }  
By removing the setter, one doubt will come to mind: How do we set the value to class properties?
So what we will do is, we will go and create the constructor, via this constructor during the object initialization we will go and pass the data. 
Create constructor and initialize the data.
  1. Public state(string name)  
  2. {  
  3. _ statename=name;  
  4. }  
Let's pass the data to the class by creating the object.
  1. Static void Main(string[] args)    
  2. {    
  3. State stateobj=new state(“Karnataka”);    
  4. Stateobj. Statename=”Goa”;// we have removed the setters , no one can reset the data externally.    
  5. }   
In the above code snippet, we can observe that I have tried assigning the data using the object but the compiler will throw an error. Why? Because we have removed the setter in class.
But internally some logic can modify the data by using the object. This can be avoided by making variable read-only.
Declare a variable as read-only.
  1. Private readonly string _ statename;  
Finally summarizing the 3 steps:
  1. Go ahead and remove the setters.
  2. Create a constructor for loading the data.
  3. Make it variable as read-only


In this blog, we have discussed the life cycle of immutable objects.