C# Interview Question #103
What is immutability in C#?
Types, Equality, Immutability & Internals Senior Advanced
Quick Interview Answer
An immutable object cannot have its observable state changed after creation. Instead of modifying an existing object, code creates a new value representing the changed state.
Detailed Explanation
An immutable object cannot have its observable state changed after creation. Instead of modifying an existing object, code creates a new value representing the changed state.
Immutability can simplify reasoning, reduce accidental side effects, and make concurrent code safer. Records, readonly fields, init-only properties, readonly structs, and immutable collections can support immutable designs.
Not every application object must be immutable. Entities managed by EF Core are often mutable, while DTOs, value objects, commands, and configuration models are strong candidates for immutability.
Code Example
public record Money(decimal Amount, string Currency);
var original = new Money(100, "USD");
var updated = original with { Amount = 120 };