A Deep Dive into Immutability in C#

C# Tutorials

Immutability is a design principle that states that the state of an object cannot be altered after the object has been created. While at first glance this may seem like a simple concept, it can have profound implications on how developers design their codebase.

Immutability is a built-in feature of the C# programming language th6at can make your code more predictable, reliable, and testable. This programming tutorial talks about immutability in C#, its benefits, and how you can implement it in C#.

If you are looking to learn C# software development in a course setting, we have a list of the Best Online Courses to Learn C# to help you get started.

What is Immutability?

Immutability is a concept that refers to the inability of a value to change once it has been set. It is a property of variables, or any other object type in C#. If an object cannot be altered after it is created, it is considered immutable.

Immutability is a property of data structures in which the value of an object cannot change after it has been created. Immutable objects are beneficial for multi-threaded applications because they do not require synchronization.

In simple terms, it is the ability of an object to remain unchanged after it is created. The word “immutable” means unchanging over time. In the context of programming, an immutable object is an object whose state cannot be modified after it is created.

Immutability in C#

Most programming languages have some notion of immutability, but the concept is particularly relevant to C# because the language was designed with immutability in mind from the beginning.

The designers of C# wanted to make it easy for developers to create immutable types, and as a result, the language has several features that support immutability. One example of an immutable type in C# is the string type. Once a string instance is created, its value cannot be changed.

This does not mean that strings cannot be modified in C#; it is just that any modification creates a new string instance rather than modifying the existing one.

How to Create an Immutable Class in C#

Programmers must adhere to a few rules to create an immutable class in C#. The first step is to make all the fields in your class read-only. This can be done by using the read-only keyword when declaring the fields. You can initialize read-only fields only in the class’s constructor. This ensures that once an object of the class is created, its field values cannot be changed.

Secondly, ensuring that any other class cannot inherit your class is crucial. It would help if you used the sealed keyword in the class declaration to do this. A sealed class cannot be inherited from, meaning developers can not change its internal state using sub-classes.

As a final step, you should ensure that your class is not exposed to objects that are mutable. This means ensuring that any references to mutable objects are either wrapped in an immutable type or marked as volatile.

By doing this, developers can be sure that even if a mutable object somehow finds its way into your immutable class, it will not be able to change anything inside it.

Read: The Top Task Management Tools for Developers

Creating an Immutable Class in C#

Here is a simple example code of an immutable class in C#:

    public class Customer
    {
        public Guid Id { get; init; }
        public string LastName { get; }
        public string FirstName { get; }

        public Customer(string firstName, string lastName)
        {
            Id = Guid.NewGuid();
            FirstName = firstName;
            LastName = lastName;
        }
    }

Note that none of the properties of this class have a public setter. You can only assign values to the properties by invoking the constructor at the time of instantiating the class.

Programmers can also make their class immutable by using read-only fields. This ensures that once an object of the class is created, its field values cannot be changed:

 
public class Customer
{
   public readonly Guid Id;
   public readonly string FirstName;
   public readonly string LastName;
   public Customer(string firstName, string lastName)
   {
       Id = Guid.NewGuid();
       FirstName = firstName;
       LastName = lastName;
    }
}

Immutability and Record Types in C#

Immutability is a built-in feature of the C# programming language, which ensures that an object cannot be modified after it is defined. Record types are immutable by default, due to which you can not change any of the properties of a record after creating an instance of it. This explains why instances of record types are often used as method parameters when passing data around in your application. This allows developers to ensure that those parameters cannot be changed after they are passed into other functions or methods.

The following code example illustrates how a record type can be declared in C#:

    public record Customer
    {
        public Guid Id { get; init; } = Guid.NewGuid();
        public string FirstName { get; init; }
        public string LastName { get; init; }
    }

You can instantiate the record type named Customer as shown below:

var customer = new Customer
{
    FirstName = "Joydip",
    LastName = "Kanjilal"
};

Immutability and Data Transfer Objects

Immutable types are typically used to create Data Transport Objects (DTOs). DTOs are types (classes and structs in C#, to be more precise) that hold data but don’t have any business logic. DTOs are a great way to pass data between different parts of your application or applications. They are commonly used to transfer data between other parts of an application.

The advantage of using a DTO over just passing around objects is that they ensure that once the object is created, it is not modified by any other part of the program. Because of this, there is no need to worry about concurrency issues or stale data, when a new version of your DTO is created. You can use a class that has read-only fields or one that doesn’t have setters or a record type as your DTO.

Final Thoughts on Immutability in C#

The idea of immutability is simple: objects that are immutable can never change their state after they have been created. That means you can’t modify the value of an immutable object or its fields. While this may seem like a limitation—but in reality, it’s actually quite useful.

Read more C# programming tutorials and software development tips.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read