Immutable objects and data structures

Immutable types are normally thought of as just value types. With value types, it makes sense that when they are set, you don't want them to change. But you can also have immutable object types and immutable data structure types. Immutable types are a type whose internal state does not change once they have been initialized.

The behavior of immutable types does not astonish or surprise fellow programmers and so conforms to the principle of least astonishment (POLA). The POLA conformity of immutable types adheres to any contracts made between clients, and because it is predictable, programmers will find it easy to reason about its behavior.

Since immutable types are predictable and do not change, you are not going to be in for any nasty surprises. So you don't have to worry about any undesirable effects due to them being altered in some way. This makes immutable types ideal for sharing between threads as they are thread-safe and there is no need for defensive programming.

When you create an immutable type and use object validation, you have a valid object for the lifetime of that object.

Let's have a look at an example of an immutable type in C#.

An example of an immutable type

We are now going to look at an immutable object. The Person object in the following code has three private member variables. The only time these can be set is during the creation time in the constructor. Once set, they are unable to be modified for the rest of the object's lifetime. Each variable is only readable via read-only properties:

namespace CH3.ImmutableObjectsAndDataStructures
{
public class Person
{
private readonly int _id;
private readonly string _firstName;
private readonly string _lastName;

public int Id => _id;
public string FirstName => _firstName;
public string LastName => _lastName;
public string FullName => $"{_firstName} {_lastName}";
public string FullNameReversed => $"{_lastName}, {_firstName}";

public Person(int id, string firstName, string lastName)
{
_id = id;
_firstName = firstName;
_lastName = lastName;
}
}
}

Now we have seen how easy it is to write immutable objects and data structures, we will look at data and methods in objects.