Reputation: 4611
Can any one help me in finding the basic difference between mutable and immutable?
Upvotes: 6
Views: 7762
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
Reputation: 11
Advantages of Immutability:
1 Thread Safety
2 Sharing
3 Less error prone
So prefer immutability, if you have the choice. :)
Upvotes: 1
Reputation: 838186
Immutable means "cannot be modified after it is created".
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
Reputation: 171
Immutable variables using in functional languages. Using a term variable is inappropriate and functional programmers prefer the term value.
Upvotes: 1
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
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
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