IMMUTABLE TYPES


The immutability is a very simple and powerful concept in c#. The object's can be two types .they are mutable and immutable.

When we can say the object is immutable?

If the object state does not change after the creation means we calling that object as immutable. Mutable is a contrast of immutable.

What is the need of immutable?

When we using a global variable in program the variable value change for different process. So the often changing makes some side effects in another process. To avoid that side effect we going for immutable class.

Let we discuss the immutable with string.
Consider a string   "a" as "meet"

string
a = "meet";
in memory we allocated space for "a".In basic the string is nothing but collection of characters.in menory we storing the staing as char array.
then take next string "b" as 

string
b = "me";
as like "a"  "b" also stored in memory as char[].

string
c = a + b; 

when we appending string "a" and "b" based upon the size of string "c" the byte will stored in memory. 

Let we explain this in real time as 

Three friend's booking ticket .They get the seat number's as 22,23,24.After the booking one more friend also like to come.Then again going for online they got the ticket for seat no 26. 

What the friends will decide in this sitution? 

Most probable answer is they cancel the before ticket and go for four serieal seat like 22,23,24,25.they search some more ticket reservation. 

So we can conclude like the string "c" also prefer sequence block to store the character array.So we calling this string as immutable type object.

Immutable class:

Two key words "const" and "readonly" achieved immutability  in c#. When we using this keywords we can't change the state of that object. Readonly allow to the change the state in constructor but we change for const.

The immutablibity have both advantages and disadvantages in equal.
Advantages: Can avoid side effects
Disadvantages: Affect efficiency.