Advertise with us

how to create an immutable class in c# explain advantage of immutable class over normal class?

Hi developers!
what is immutable in c # and how to create an immutable class in c# explain advantage of immutable class over normal class?
thanks in advance!
Last updated:7/31/2013 12:52:01 AM

1 Answers

shreesh chandra shukla
shreesh chandra shukla

In object-oriented programing and functional programming, an immutable object is an object whose state cannot be modified/changed after it is created.  Which in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally-used attributes change but the object's state appears to be unchanging from an external point of view. Immutable objects are often very useful because they are inherently thread-safe (i.e. if you are to accessing immutable object through threads, there are no chance to  get(read )inconsistence state(i.e. value ) of that object because once immutable objects never override its value  at same reference). Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.


The classical example of immutable objects are java’s String class. Which never changed at the same reference, if you modify the objects states.

String s=”hello”;

S=s.toUpper();//modified immutable objects s to upper case;

In this case actual object “s” is not modified, instead it makes new object with same name with modified value.

There are following merits/advantage of Immutable objects: because they

1.   are very easy to construct, test, and use

2.   Are by default thread-safe and have no explicit synchronization is needed.

3.   do not  have need  for a copy constructor

4.   do not need an implementation of is objects  cloning

5.   are able to create  good Map keys and Set elements (these objects must not change state while in the collection)

6.   if an immutable object throws an exception, it's never left in an undesirable or indeterminate state


Last updated:7/31/2013 12:52:01 AM