WHAT IS IMMUTABLE IN C # AND HOW TO CREATE AN IMMUTABLE CLASS IN C# EXPLAIN ADVANTAGE OF IMMUTABLE CLASS OVER NORMAL CLASS?

Andrew Deniel

Total Post:29

Points:203
Posted by  Andrew Deniel
C# 
C#
 1496  View(s)
Ratings:
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!
  1. shreesh chandra shukla

    Post:105

    Points:735
    Re: what is immutable in c # and how to create an immutable class in c# explain advantage of immutable class over normal class?

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!