Tuesday, May 3, 2011

Immutable types in DotNet


What are immutable types?

You can say class is immutable if you cannot change the value of its instances once assigned.

Most of the people know ‘string’ is immutable type when you change or modify value of string it will create new string object. It is recommended to use StringBuilder class instead of string if you want to change/modify string value frequently. But this is not the only immutable type available in dotnet there are many other immutable types also available in dotnet.

Delegates are also immutable types when you assign any function to delegate using += sign it will create new object internally. Anonymous type is also one of the example of immutable type when you create anonymous types you can not change value of its member. You can also create your own immutable types in C#. To create custom immutable type you can use const and read-only keyword in C#

Create immutable types in C#

    public class MyImmutableType
    {
        public const string Name = "Mitesh";
        public readonly int Age;
        public MyImmutableType(int age)
        {
            Age = age;
        }
    }

As per above example, you can assign Age property only once when you create an instance of MyImmutableType class. Once instance is created you can't change the value of Age property.

Create immutable types using Anonymous Types in C#

var myType = new { Name = "Mitesh", Age = 29 };
      myType.Age = 58 //Compiler error

By default anonymous types are immutable so you cannot change the value of any members of anonymous type.

Benefits of immutable types

Immutable types can be used in multi threading programming where multiple threads trying to access same data. The same time it is difficult to manage write and read access of it. You can use immutable types in such scenarios. One more place where you can use immutable type is to create Hashtable Keys. In common scenario where you want your data to be persisted once assigned but not want to modify or change in this case you can also go for immutable types.

No comments:

Post a Comment