Immutability

suggest change

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). IEnumerable<Student> hides Add, but it still shares the original list. Copy the elements into a ReadOnlyCollection<Student> when later changes to the caller’s list must not appear:

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

    public Classroom(IEnumerable<Student> students)
    {
        Students = new ReadOnlyCollection<Student>(students.ToArray());
    }
}

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

With the immutable object we have the following benefits:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents