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
- string myString = “hihihello”;
- myString .Replace(“hihihello”, “OO”);
-
- …But, we need to write like below:
-
- 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,
- Programmers or Developers will never get race conditions because of a corrupted String.
- Strings are well adapted to be key in Hashtable or Disctionary like below,
- Sytem.Collections.generic.Dictionary<K,V>).
- 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
- string str1 = “moomoo”;
- string strFoo = “moo”;
-
- string str2 = strFoo + strFoo;
-
-
-
-
- Debug.Assert(str1 == str2);
How to Create an Immutable Class?
The steps are given below to create Immutable class in .NET-
- Declare the class as Sealed so can't be extended.
- Make all the fields private, so that direct access can't be done.
- Remove Setter method of all the properties.
- Make all mutable fields sealed, so that value can be assigned only once.
- Initialize all the fields via constructor.
Example
- public class MyImmutableClass
- {
- public readonly int MyValue1;
- public readonly string MyValue2;
-
-
-
- public ProgressStatus (int myValue1, string myValue2)
- {
-
- MyValue1= myValue1;
- MyValue2= myValue2;
-
- }
- }
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-
- Simplicity - It provides only one state for each class.
- Thread Safe - It is thread safe because the state can't be changed and therefore no synchronization is required.
- 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.
Former memberPosted Oct 19, 2016, 1:27 PM
Conceptually, it can make more sense to be immutable. If we add a month onto Christmas, we haven't changed Christmas, we have produced a new date in late January. It makes sense therefore that Christmas.AddMonths(1) produces a new DateTime rather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.
Former memberPosted Oct 19, 2016, 1:26 PM
Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interferes with another is removed (the reference itself is a different matter).
Vinod GuptaPosted Oct 19, 2016, 9:05 AM
Actually String (Interned) is NOT immutable in real sense if you consider some deep aspects around it. If you try to create string a, b and c in one thread and same strings a, b and c in another thread, CLR does the garbage collect these strings and returns the reference of earlier created strings (from first process)to the new request (from second process), this it becomes mutable. Strings can be shared across multiple AppDomains. mscorlib.dll loads in domain-neutral way which contains System.String type and since this DLL loads in domain-neutral fashion so the strings can be shared across multiple AppDomains hence become non-immutable!
Satish Kumar VadlavalliPosted Oct 18, 2016, 8:56 AM
Good article, keep up good work