Introduction
In programming, mutability refers to whether or not the value of an object can be changed after it is created.
Mutable → Can be changed after creation
Immutable → Cannot be changed once created (a new object is created instead)
Mutability affects memory usage, performance, and behavior—especially when passing objects between functions or working with collections.
Let’s explore what this means with examples .
What is a Mutable Type?
A mutable type is one whose internal state (its data) can be modified without creating a new object.
Example: Mutable Object (C# List)
List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4); // modifies the same list
Console.WriteLine(string.Join(", ", numbers)); // Output: 1, 2, 3, 4
Here:
The same
numbersobject is changed in memory.No new list is created.
Common Mutable Types in C#
List<T>Dictionary<TKey, TValue>ArrayStringBuilder
What is an Immutable Type?
An immutable type is one whose value cannot change once it’s created.
If you try to modify it, a new object is created instead.
Example: Immutable Object (C# String)
string name = "Raj";
name += " Bhatt";
Console.WriteLine(name); // Output: Raj Bhatt
But internally:
A new string
"Raj Bhatt"was created.The original
"Raj"string remains unchanged.
Common Immutable Types in C#
stringint,double,decimal,boolDateTimeGuidTupleRecordtypes (introduced in C# 9+)
Mutable vs Immutable — Key Differences
| Feature | Mutable | Immutable |
|---|---|---|
| State Change | Can change internal data | Cannot change after creation |
| Memory Usage | Usually efficient (same object modified) | May create new objects |
| Thread Safety | Not thread-safe by default | Naturally thread-safe |
| Examples | List, Dictionary, StringBuilder | String, int, Record, DateTime |
| When to Use | When frequent updates are needed | When consistency and safety matter |

Join the conversation! Your thoughts help the community grow.