Concept of Immutable Objects in C#

This article provides an insight about immutable objects -- classes, data types etc. -- in C#. We will also the cover the differences between immutable and mutable types in C#.

Introduction

Anything that is immutable implies that it is read-only/static. To put it in simpler words, the value of the immutable types do not change over the course of execution.

Immutable Classes

To implement the concept of immutable classes, you can choose to have the properties of that class as public but with only "getter" methods defined. No setter for the properties should be available.

Other things to keep in mind while creating an immutable class:

  1. The member variables corresponding to the properties should be private.
  2. The class should implement a parameterized constructor through which the values of properties can be set.

Sample code below

  1. public class ImmutableClass  
  2. {  
  3.   
  4.     private string name;  
  5.     public string Name  
  6.     {  
  7.         get//no setter defined  
  8.     }  
  9.   
  10.     public ImmutableClass(string nameVal)  
  11.     {  
  12.         this.name = nameval;  
  13.     }  
  14. }  
Immutable DataTypes

String is one of the immutable data types that is available in C#. While string is a reference type (theoretically), it appears to behave like a value type. Whenever an append operation is performed on a string, it appears like the same object is updated but behind the screens it behaves in an entirely different way.

For every append operation performed, a new string object is created and the older is available for the garbage collector to collect. Hence, string in C# is immutable.

Sample code
  1. string dummy = "immutable";  
  2. dummy += "String";  
Now, here the string "immutable" is available for the garbage collector to collect and a new object is created for "immutableString".

Hope this clarifies the "immutable types" in C#.

Difference between Immutable Types and Mutable Types

String is immutable and StringBuilder is mutable. To elaborate, when we use StringBuilder, the same object is used to hold the new value, unlike String.

Sample code for illustration
  1. StringBuilder sb = new StringBuilder("Hello");  
  2. sb.Append("Hi");  
The new string "HelloHi" is assigned to the same object as "Hello."