Mutable & Immutable Classes

This post describes a method for creating a mutable and immutable version of the same class. At a first glance, there may seem to be two obvious ways to approach this problem; either:

  1. Create a base Mutable Class and derive a Immutable version of this class; or
  2. Create a base Immutable Class and derive a Mutable version of this class.

To help decide which may be the best design, we can refer back to the principles of object-oriented design. The Liskov Substitution Principle states that subtypes must be substitutable for their base types.

Don’t inherit unless you really are (and can be treated in all respects) like what you derive from.

Keeping this in mind, we can see that solution one would violate this principle. You can not treat an Immutable object as a Mutable object. i.e. you would not want a user to be able to cast an immutable object, to it’s parents-type, so that the user could then mutate that object.

A simple implementation of solution two is shown below.

    public class ImmutableClass
    {
        public int SomeProperty { get; protected set; }
        public string AnotherProperty { get; protected set; }
    }

    public class MutableClass : ImmutableClass
    {
        public new int SomeProperty
        {
            get
            {
                return base.SomeProperty;
            }
            set
            {
                base.SomeProperty = value;
            }
        }

        public new string AnotherProperty
        {
            get
            {
                return base.AnotherProperty;
            }
            set
            {
                base.AnotherProperty = value;
            }
        }
    }