Making the world a better place, one line of code at a time

Immutability, part 1: Read-only vs. Immutable

Posted on Tuesday, June 11, 2013

A read-only object is an object that does not expose any way to change it. ReadOnlyCollection<T> (returned by AsReadOnly()) is a good example). However, IEnumerable<T> is also read-only.
The important distinction is that read-only objects are allowed to change.

If you write list.Add(new Test()), your read-only collection (which just wraps list) will have changed.

Read-only collections are useful for designing safe APIs, where only the owner of the collection is allowed to change it.
However, it won’t do any good for thread-safety.

An immutable object is an object that cannot change at all, no matter what happens (Reflection doesn’t count). string is an excellent example of an immutable class; the value of an existing string instance can never change, no matter what happens. (barring reflection, unsafe code, and certain marshalling tricks)

.Net does not have any built-in immutable collections, but the CLR team released a library of immutable collection types on NuGet.

Truly immutable objects are intrinsically thread-safe. Since there is no way to modify them, there is no chance that other threads will observe an inconsistent instance.

In summary, there are four kinds of “unchangeable” things:

Finally, an object is deeply immutable (or read-only) if both it and all of its properties are also deeply immutable (or read-only). In other words, the entire graph of objects reachable from it must be immutable (or read-only).

Next time: Creating a simple immutable stack

Categories: C#, oop, thread-safety, immutability Tweet this post

comments powered by Disqus