Jaa


Creating Immutable types

Someone asked on a C# DL "How do I create an immutable type"

The answer was obviously by creating a type in which you don't allow writeable fields or properties or have methods that change the state of the type. However, the questions started revolving around how System.String have methods to update the string but in reality it creates a new instance. All of this is really simple to achieve.

Lets think of an Employee immutable class, where the class has a Name and Salary property and allows an increment to be made to the Salary. However, since Employee is immutable the Increment results in a new instance of the class to be created with an incremented Salary.

 class Employee
{
    public Employee(string name, uint salary)
    {
        this.name = name;
        this.salary = salary;
    }

    public Employee Increment(uint delta)
    {
        // A new instance is created
        return new Employee (this.Name, this.Salary + delta);
    }

    readonly string name;
    public string Name { get { return name; }}

    readonly uint salary;
    public uint Salary { get { return salary; }}
}

In the code above there is no field and the properties are get only. So there is no possibility of making state changes with these. The Increment method creates a new instance of the class with the increment without touching the class on which it is called. All of this makes Employee an immutable type.

Comments

  • Anonymous
    December 21, 2006
    Hmmm...why not use the readonly keyword on the name and salary fields?i.e.: readonly string salary;-- PBR
  • Anonymous
    December 21, 2006
    Oops missed readonly :(I have updated the code.
  • Anonymous
    July 07, 2009
    void Main(){ var emp = new Employee("bob", 10000); MakeNull(emp); Console.WriteLine(emp.Name);//null reference exception } void MakeNull(Employee emp) { emp = null; } classes can't be truly immutable in C#