C# - Mutable and Immutable objects

In C#, mutable and immutable are terms used to describe whether the state of an object can be changed after it is created.

Mutable refers to something that can be altered, whereas immutable indicates something that cannot be changed. For primitive data types like int and decimal, they are mutable. This means that when we create an object of these types and change its values repeatedly, the location where it's stored in memory stays the same.

Mutable Objects

Definition: A mutable object can have its state or content changed after creation. You can alter its properties, fields, or elements.

Example: List<int>

List<int> numbers = new List<int> {1, 2, 3};
Console.WriteLine("Original list: " + string.Join(", ", numbers));

// Modifying the list by adding a new number
numbers.Add(4);
Console.WriteLine("Modified list: " + string.Join(", ", numbers));
    

Output:

Original list: 1, 2, 3
Modified list: 1, 2, 3, 4
    

Explanation: The list numbers is mutable. Adding a new element (4) changed the state of the object.

Immutable Objects

Definition: An immutable object cannot be altered once created. Any modifications result in the creation of a new object.

Example: String Class

string greeting = "Hello";
Console.WriteLine("Original string: " + greeting);

// Attempting to modify the string
string modifiedGreeting = greeting + ", World!";
Console.WriteLine("Modified string: " + modifiedGreeting);
    

Output:

Original string: Hello
Modified string: Hello, World!
    

Explanation: When modifying greeting by adding ", World!", a new string modifiedGreeting is created. The original greeting remains unchanged.

Understanding mutable and immutable objects in C# is important for memory management and performance. Mutable objects allow changes but can lead to unintended side-effects, whereas immutable objects offer predictability and thread safety but may increase memory usage and processing time due to the creation of new objects for any modifications.

Why Strings are Immutable in C#?

Strings in C# are immutable for several reasons, primarily relating to efficiency, security, and design simplicity. Here's a step-by-step explanation:

1. Memory Efficiency

Interning: C# stores strings in an intern pool to save memory. If two strings have the same content, they point to the same memory location.


string a = "Hello";
string b = "Hello";
// Both 'a' and 'b' refer to the same location in memory

2. Security

Immutable Nature: The immutability of strings ensures their hashcode remains constant, crucial for security in scenarios like hash tables.


string password = "securepassword";
// Once set, 'password' cannot be altered in memory

3. Simplified Operations and Thread Safety

Predictability and Thread Safety: Operations on immutable strings are predictable, and their unchangeable nature makes them thread-safe.


string message = "Original Message";
string newMessage = message.Replace("Original", "New");
// Creates a new string, 'message' remains unchanged

4. Performance Optimization

Reduced Overhead: Immutable strings reduce the need for copying and handling, optimizing performance.


string name = "John";
// Passing 'name' to a method is efficient as it's a reference
Greet(name);

Drawbacks and Workarounds

Memory Overhead: The creation of new strings for modifications can increase memory usage. StringBuilder is a workaround for frequent modifications.


StringBuilder sb = new StringBuilder("Hello");
sb.Append(", World!");
// Efficient for multiple modifications

In summary, strings are immutable in C# to optimize memory usage, ensure security, simplify programming, and maintain thread safety. While there are a few drawbacks, the benefits significantly outweigh them in most cases.