All About C# Immutable Classes

Atul Sharma

Our first encounter with Immutable word happens when we read strings are immutable. On the same line, we can have Immutable Classes. In this article, we are going to cover all necessary information needed to know about it in C#.

What is an Immutable Class?

Google gives the following definition about

Immutable Classes
Google Definition of Immutable

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

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

When to use an Immutable Class?

Based on the virtue of being unchangeable in future, we can use immutable classes in 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.
See also  Dynamics 365: Type of Forms

How to implement Immutable Class?

There are two ways to implement 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 at all they are good to be used across different threads.

Immutable classes are Always in Valid State

While creation, we check the validity of all fields and later they can not 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 fields.

See also  Basic concepts in C#
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 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 code more readable and maintanable.

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.

Does Immutable class need to be “Sealed”?

Since Immutable Class in C# is NOT a language feature and it is supposed to have constant information, we can make it sealed so that it can NOT be altered after being derived.