Immutable Object in C#

Introduction
 
Sometimes we need to load application data like language, currency settings at the start of application. And those information we are not going to change anymore. In this scenario we can use Immutable object concept.
 
Immutable object means it cannot be changed internal/external once object is created. A class is immutable when instance of class is immutable.
 
It can be used in Master data(load all application level data), configuration data and singleton design pattern.
 
One good example immutable class is System.String. When you modify a string, it creates a new string object.
 
string myName = "Manas"; // First time it creates a new object.
myName = "Mohapatra"; // It create a new object of string type
 
Implementation
 
In below code snippet, it has one public class and it contains two readonly properties and one parameterized constructor. Firstly, about properties are readonly because it's value can be change till object creation through constructor and it has only get attribute to return no set attribute. Secondly, about parameterised constructor which receives two params and assigns those readonly properties.
  1. public class AppSeting  
  2. {  
  3.     private readonly string _Version;  
  4.   
  5.     public string Version  
  6.     {  
  7.         get { return _Version; }  
  8.     }  
  9.       
  10.     private readonly string _Language;  
  11.     public string Language  
  12.     {  
  13.         get { return _Language; }  
  14.     }  
  15.       
  16.     public Currency(string version, string language)  
  17.     {  
  18.         _Version = version;  
  19.         _Language = language;  
  20.     }  
  21. }  
Once class is declared, next is to create instance of class and pass parameters to constructor. You can get the value through object.properties. However if you try to assign value to properties then you will get compilation error. Because we don't have any set attribute in properties only get is defined. So our class is immutable. 
  1. // Create object and pass value to constructor  
  2. AppSeting appObj = new AppSeting("1.0""EN");  
  3. Console.WriteLine(appObj.Version); //1.0  
  4.   
  5. appObj.Version = "2.0"// Get compilation error  
  6. appObj.Language = "FR"// Get compilation error  
Conclusion
 
Here we discussed about Immutable object in C#. Use it as per scenario.
 
Hope this helps.