Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between mutable and immutable?

Tags:

c#-4.0

Can any one help me in finding the basic difference between mutable and immutable?

like image 651
Hemant Kumar Avatar asked Sep 28 '10 08:09

Hemant Kumar


People also ask

What is difference between mutable and immutable explain with example?

To summarise the difference, mutable objects can change their state or contents and immutable objects can't change their state or content. Immutable Objects : These are of in-built types like int, float, bool, string, unicode, tuple. In simple words, an immutable object can't be changed after it is created.

What is difference between mutable and immutable files?

Mutable: Mutable means whose state can be changed after it is created. Immutable: Immutable means whose state cannot be changed once it is created.

What is the difference between mutable and immutable string?

a mutable string can be changed, and an immutable string cannot be changed.


3 Answers

Immutable means that once initialized, the state of an object cannot change.

Mutable means it can.

For example - strings in .NET are immutable. Whenever you do an operation on a string (trims, upper casing, etc...) a new string gets created.

In practice, if you want to create an immutable type, you only allow getters on it and do not allow any state changes (so any private field cannot change once the constructor finished running).

like image 175
Oded Avatar answered Nov 12 '22 22:11

Oded


A very basic definition would be:

Mutable Objects: When you have a reference to an instance of an object, the contents of that instance can be altered

Immutable Objects: When you have a reference to an instance of an object, the contents of that instance cannot be altered

like image 36
Dirk Vollmar Avatar answered Nov 12 '22 21:11

Dirk Vollmar


Immutable means "cannot be modified after it is created".

  • An immutable type has a constructor and getters but not setters.
  • A mutable type can also have setters.

An example of an immutable type is DateTime. The method AddMinutes does not modify the object - it creates and returns a new DateTime.

Another example is string. For a mutable class similar to string you can use the class StringBuilder.

There is no keyword in C# to declare a type as immutable. Instead you should mark all member fields as readonly to ensure that they can only be set in the constructor. This will prevent you from accidentally modifying one of the fields, breaking the immutability.

like image 31
Mark Byers Avatar answered Nov 12 '22 23:11

Mark Byers