Welcome to MSDN Blogs Sign in | Join | Help

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.

Published Thursday, December 21, 2006 1:42 PM by abhinaba
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Creating Immutable types

Thursday, December 21, 2006 4:51 PM by PBR

Hmmm...why not use the readonly keyword on the name and salary fields?

i.e.: readonly string salary;

-- PBR

# re: Creating Immutable types

Friday, December 22, 2006 1:35 AM by abhinaba

Oops missed readonly :(

I have updated the code.

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker