C# Language Immutability


Example

Immutability is common in functional programming and rare in object oriented programming.

Create, for example, an address type with mutable state:

public class Address () 
{
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City  { get; set; }
}

Any piece of code could alter any property in the above object.

Now create the immutable address type:

public class Address () 
{
    public readonly string Line1;
    public readonly string Line2;
    public readonly string City;

    public Address(string line1, string line2, string city) 
    {
        Line1 = line1;
        Line2 = line2;
        City  = city;
    }
}

Bear in mind that having read-only collections does not respect immutability. For example,

public class Classroom
{
    public readonly List<Student> Students;
    
    public Classroom(List<Student> students)
    {
        Students = students;
    }
}

is not immutable, as the user of the object can alter the collection (add or remove elements from it). In order to make it immutable, one has either to use an interface like IEnumerable, which does not expose methods to add, or to make it a ReadOnlyCollection.

public class Classroom
{
    public readonly ReadOnlyCollection<Student> Students;

    public Classroom(ReadOnlyCollection<Student> students)
    {
        Students = students;
    }
}

List<Students> list = new List<Student>();
// add students
Classroom c = new Classroom(list.AsReadOnly());   

With the immutable object we have the following benefits:

  • It will be in a known state (other code can't change it).
  • It is thread safe.
  • The constructor offers a single place for validation.
  • Knowing that the object cannot be altered makes the code easier to understand.