DEV Community

Cover image for Immutability with Init-Only Properties in C#
neophyte
neophyte

Posted on

Immutability with Init-Only Properties in C#

In C#, immutability refers to the property of an object that once it is created, its state cannot be changed. This is typically achieved by making sure that the object's properties cannot be modified after the object is instantiated. One way to achieve immutability in C# is by using init-only properties, introduced in C# 9.0.

Init-only properties allow you to set the initial values of properties when an object is created, but they cannot be modified afterwards. This ensures that the object's state remains constant after it's been constructed. Here's how you can achieve immutability using init-only properties:

public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the FirstName and LastName properties are declared as init-only properties using the init accessor. The constructor initializes these properties, and once the object is created, their values cannot be changed.

Here's how you can use this Person class:

var person = new Person("John", "Doe");

// This will result in a compilation error because init-only properties cannot be modified after initialization.
// person.FirstName = "Jane";

Console.WriteLine($"{person.FirstName} {person.LastName}");

Enter fullscreen mode Exit fullscreen mode

Attempting to modify the FirstName property after initialization will result in a compilation error, enforcing the immutability of the object's state.

Init-only properties provide a convenient way to create immutable objects without the need to write custom getter methods and private setters, as was required in previous versions of C#. They improve code readability and maintainability by clearly indicating which properties are intended to be set only during object initialization.

Keep in mind that while init-only properties prevent you from directly modifying the property values, they do not make the entire object deeply immutable. If the properties themselves hold reference types (e.g., collections or other objects), those internal objects might still be mutable. If you want to ensure complete immutability, you need to ensure that the entire object graph is immutable.

Here is one more example which is mostly use in Domain Driven style codebase.

public abstract class Entity
{
    protected Entity(Guid id) => Id = id;

    protected Entity() { }

    public Guid Id { get; private init; }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading.

Top comments (0)