All About C# Immutable Classes

Our first encounter with the word "Immutable" happens when we read strings are immutable. On the same line, we can have immutable classes.

What is an Immutable Class?

Google gives the following definition of immutable.

C# Immutable Classes 

Technically, Immutable Class means a class which once created, its state cannot be changed later by any means internally or externally.

Metaphorically, it is like a ceramic pot. We can give it any shape only in the beginning when we start making it.

When to use an Immutable Class?

Based on the virtue of being unchangeable in the future, we can use immutable classes in the following situations,

  1. To replace struct (Value type) with class (reference type)
  2. General purpose classes
  3. Class with Constant fields
  4. Class with Configuration related information
  5. Class with Master data
  6. Class with Cached data in singleton classes.

How to implement the Immutable Class?

There are two ways to implement the Immutable class.

Approach #1

  1. Read Only properties
  2. Parametrized constructor to initialize properties,
    public class Writer1    
    {    
        // Read-only properties.       
        public string Name { get; }    
        public string Article { get; private set; }    
    
        // Public constructor.       
        public Writer1(string authorName, string articleName)    
        {    
            Name = authorName;    
            Article = articleName;    
        }    
    }

Approach #2

  1. Read-Only Properties
  2. Static method
  3. Private paramterized constructor to initialize properties,
    public class Writer2    
    {    
        // Read-only properties.       
        public string Name { get; private set; }    
        public string Article { get; }    
    
        // Private constructor.       
        private Writer2(string authorName, string articleName)    
        {    
            Name = authorName;    
            Article = articleName;    
        }    
    
        // Public factory method.       
        public static Writer2 GetArticle(string name, string article)    
        {    
            return new Writer2(name, article);    
        }    
    }

Important

It is important to note that read-only properties and a parameterized constructor are key to ingredients to the recipe of immutable classes.

Benefits of Immutable Classes?

Immutable classes are Thread safe

Since their state doesn’t change at all they are good to be used across different threads.

Immutable classes are Always in Valid State

During creation, we check the validity of all fields and later they cannot be changed so they are always valid.

Immutable classes Support Defensive Copying by default

Since they are not changed once initialized, it is always safe to copy them to another object without applying validation on each field.

Immutable classes are more test friendly and easier to test

Since we know that data contained in the object is not going to change, it will be very easier to change the scenario with the constant state of the object.

With Immutable classes, debugging becomes Easier

We will know well in advance about the data in the object, debugging will be a lot easier as we will have to focus on the other areas only. It also makes the code more readable and maintainable.

How it is different from mutable/regular classes?

Other than mentioned behavior there is no change in the terms of memory or performance. It has to be used diligently and it can NOT replace all regular classes.


Similar Articles