Hemant Kumar
Hemant Kumar

Reputation: 4611

What is the difference between mutable and immutable?

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

Upvotes: 6

Views: 7762

Answers (7)

Manish
Manish

Reputation: 1

Use Reference
imaginationhunt.blogspot

IS STRING MUTABLE OR IMMUTABLE IN .NET?

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

String objects are 'immutable' it means we cannot modify the characters contained in string also operation on string produce a modified version rather than modifying characters of string.

Upvotes: 0

Advantages of Immutability:

1 Thread Safety
2 Sharing
3 Less error prone

So prefer immutability, if you have the choice. :)

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838186

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.

Upvotes: 3

ASergan
ASergan

Reputation: 171

Immutable variables using in functional languages. Using a term variable is inappropriate and functional programmers prefer the term value.

Upvotes: 1

Oded
Oded

Reputation: 499002

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).

Upvotes: 13

Dirk Vollmar
Dirk Vollmar

Reputation: 176169

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

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

An immutable type cannot be changed once instantiated. For example strings are immutable. Every time you want to change the value of a string a new instance is created.

Upvotes: 2

Related Questions