Home > DeveloperSection > Forums > what is immutable in c # and how to create an immutable class in c# explain advantage of immutable class over normal class?
Andrew Deniel
Andrew Deniel

Total Post:29

Points:203
Posted on    July-27-2013 8:22 AM

 C# C# 
Ratings:


 1 Reply(s)
 1073  View(s)
Rate this:
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!


shreesh chandra shukla
shreesh chandra shukla

Total Post:105

Points:735
Posted on    July-31-2013 12:52 AM

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.

Example:

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

Thanks.


Don't want to miss updates? Please click the below button!

Follow MindStick