Immutable Objects

Introduction

Immutable Objects follow a famous quote: "Make the Pot While the Mud is Wet." Once the mud become dry, it can't be changed. Immutable objects are also called unchangeable objects whose state can't be modified after they are created.
 
In some cases the object's internally used attribute changes but the object's state doesn't change from an external point of view. So, in this case these objects are also called immutable objects. State of object is the important part to make it immutable.
 
Strings and other Concrete objects are called Immutable objects. It increases readability and run time efficiency in OOPS. Immutable objects are very useful in every case because  these are thread safe.
 
Thus, immutable objects are those objects, whose state can't be altered or changed internally or externally. Basically, these fields or properties are declared read-only and are fully initialized during construction. 

String - A Famous Immutable Class

System.String is a famous immutable class. It can't be modified. Whenever we try to modify a string but it doesn't modify; it creates a new string object.
 
Example 
  1. string myString = “hihihello”;  
  2. myString .Replace(“hihihello”, “OO”);  
  3.   
  4. …But, we need to write like below:  
  5.   
  6. myString = myString .Replace(“hihihello”, “OO”);  

Why .NET Engineers decided that String Should be Immutable?

.NET Engineers decided to make String Immutable due to below reasons,
  1. Programmers or Developers will never get race conditions because of a corrupted String.
  2. Strings are well adapted to be key in Hashtable or Disctionary like below,
    1. Sytem.Collections.generic.Dictionary<K,V>).  
  3. Even though, System.String is a class, string objects get compared with equivalence, as a value type. This is possible because it is an immutable object and it maintains the state.
Example         
  1. string str1 = “moomoo”;  
  2. string strFoo = “moo”;  
  3.   
  4. string str2 = strFoo + strFoo;  
  5.   
  6. // Even thought str1 and str2 reference 2 different objects  
  7.   
  8. // the following assertion is true.  
  9. Debug.Assert(str1 == str2);  

How to Create an Immutable Class?

The steps are given below to create Immutable class in .NET-
  1. Declare the class as Sealed so can't be extended.
  2. Make all the fields private, so that direct access can't be done.
  3. Remove Setter method of all the properties.
  4. Make all mutable fields sealed, so that value can be assigned only once.
  5. Initialize all the fields via constructor.
Example
  1. public class MyImmutableClass  
  2. {  
  3.    public readonly int MyValue1;  
  4.    public readonly string MyValue2;  
  5.   
  6.   
  7.   
  8. public ProgressStatus (int myValue1, string myValue2)  
  9. {  
  10.       
  11.       MyValue1= myValue1;  
  12.        MyValue2= myValue2;  
  13.        
  14.    }  
  15. }  
Now, we can read or write the values of the type without holding a lock for more than a single assignment.

Reasons to Write Immutable Classes

The reasons to write immutable classes are given below-
  1. Simplicity - It provides only one state for each class.
  2. Thread Safe - It is thread safe because the state can't be changed and therefore no synchronization is required.
  3. More robust code - Just think, if the string would have not been immutable. 

Conclusion

Immutable Objects are the important part of .NET. It is like "Make the Pot While the Mud is Wet." It has several advantages. Its state can't be changed. Thus, it doesn't require Thread Synchronization. This makes it Thread safe.

Ebook Download
View all
Learn
View all