Immutable objects in C#

Words
220
Reading
1 min
Listen
Play
9y

If you make use of immutability in your code it brings a number of benefits.

  • No need to worry what you give the object to it can't change it.
  • 100% Thread safe. No locking required to share data.
  • No need to clone objects just reuse them.

Above all it just makes like easier chasing bugs, none of those subtle bugs where something changes an object it shouldn't.

In C# the basic syntax has got easier for immutable objects.

public class Person
{
    public Person(
        string title, 
        string firstName, 
        string surname, 
        DateTime dateofBirth)
    {
        Title = title;
        FirstName = firstName;
        Surname = surname;
        DateOfBirth = dateofBirth;
    }
    
    public string Title { get; }
    public string FirstName { get; }
    public string Surname { get; }
    public string DateOfBirth { get; }
}

Still somewhat bloated but not too different than a normal class definition. Notice the use of read only properties, hence needing to pass all the values when you construct it. There are a few embellishments I like to add.

public class Person
{
    public static Person Create(
        string title, 
        string firstName, 
        string surname, 
        DateTime dateofBirth)
        => new Person(title, firstName, surname, dateofBirth;

    private Person(
        string title, 
        string firstName, 
        string surname, 
        DateTime dateofBirth)
    {
        Title = title;
        FirstName = firstName;
        Surname = surname;
        DateOfBirth = dateofBirth;
    }
    
    public string Title { get; }
    public string FirstName { get; }
    public string Surname { get; }
    public string DateOfBirth { get; }
    
    public Person With(
        string title = null, 
        string firstName = null, 
        string surname = null, 
        DateTime? dateofBirth = null)
        = new Person(
            title ?? Title,
            firstName ?? FirstName,
            surname ?? Surname.
            dateofBirth ?? DateOfBirth);
}

The Create() gives Person a Tuples like syntax where you have to use Tuple.Create() to build them. With is stolen from F#.

var bob = Person.Create(
    "Mr", "Bob", "Jones", new DateTime(1960, 4, 28));

var bobUpgraded = bob.With(title: "Supreme Overlord");

So bobUpgraded is a copy of bob with a new title. It uses the named parameter syntax coupled with defaulted arguments to let you supply just the changes you want to make.

var moniedBob = bob.With(
    firstName: "Bobby", surname: "Jones-Smith");

As you can see this makes mutation easy, just in the form of a new Person object.

Immutability goes far deeper. It is a way of thinking of data and flow. If people would like me to dig deeper down the rabbit hole let me know.

Happy coding

Woz

Immutable objects in C# | Ecency