Mutable Objects vs Immutable Objects in C#

C#, mutability and immutability refer to whether or not an object’s state can be changed after it has been created.

1. Mutable Objects

  • A mutable object can be modified after its creation.
  • This means the values of the object's fields or properties can be changed, either directly or through methods that modify its state.
  • Classes are usually mutable in C#, but structs can also be mutable if designed that way.

Example of a Mutable Class


public class Person { public string Name { get; set; } public int Age { get; set; } public void HaveBirthday() { Age++; // This changes the internal state of the object } } // Usage Person person = new Person { Name = "Alice", Age = 30 }; person.Age = 31; // Directly changing a property person.HaveBirthday(); // Changes the Age property through a method

In the example above, Person is mutable because its Name and Age properties can be changed after an instance of Person is created.

2. Immutable Objects

  • An immutable object cannot be changed after it is created.
  • This means that all fields and properties of the object are set only once, typically through the constructor, and cannot be changed afterward.
  • Immutable objects are useful when you want objects that don’t change over time, which can help prevent bugs, especially in multi-threaded scenarios.
  • Examples of immutable types in C# include System.String, System.DateTime, and other simple types.

Example of an Immutable Class


public class Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } } // Usage Point point = new Point(3, 5); // point.X = 10; // Compilation error because X has no setter

In this example, Point is immutable because it has only read-only properties (X and Y) that are set once in the constructor and cannot be changed afterward.

Why Use Immutable Types?

  • Thread Safety: Immutable objects are inherently thread-safe because their state cannot change after construction.
  • Predictability: Since immutable objects cannot change, they are easier to reason about and avoid side effects.
  • Hash Codes and Dictionaries: Immutable objects work well as keys in dictionaries or hash sets because their hash codes won’t change over time.

Making Classes Immutable in C#

To create an immutable class in C#:

  1. Use readonly fields or properties with only get accessors.
  2. Set all values through a constructor.
  3. Avoid methods that modify state.

Immutable Example with a String


string name = "Alice"; string newName = name.Replace("A", "E"); // Creates a new string // The original string "Alice" is unchanged.

In the example above, string is immutable because any modification (like Replace) results in a new string rather than changing the original.

Mutable vs. Immutable Summary Table

FeatureMutableImmutable
Can be changed after creation?YesNo
Common typesClasses (e.g., List, Array)String, DateTime, custom immutable classes
Use casesWhen state changes are expectedWhen stability and thread safety are preferred

Comments

Popular posts from this blog

Performance Optimization in Sitecore

Strategies for Migrating to Sitecore from legacy or upgrading from older Sitecore

Azure Event Grid Sample code