What is immutability, and why is it valuable?
Quick Answer
An immutable object can't change after construction. Benefits: it's inherently thread-safe (no locking on shared reads), it's safe to cache and share, it can't be mutated behind your back by another part of the code, and it makes equality and hashing well-defined. C# supports it with readonly fields, init-only setters, and record types with with-expressions for non-destructive updates.
Immutability means once an object is created, its state is fixed. The payoff is mostly about reasoning and concurrency: an immutable object is automatically thread-safe because there's nothing to synchronise, you can hand the same instance to many callers without worrying one of them mutates it, and its hash code and equality stay stable so it's safe as a dictionary key. C# gives you init setters and records, where with lets you produce a modified copy instead of mutating. The cost is extra allocations if you're “changing” it repeatedly, which is where a builder or a mutable local comes in.
- Value objects in DDD (Money, DateRange) are immutable — identity is the value.
- Immutable collections (
System.Collections.Immutable) return a new collection on each change, sharing structure internally. - Downsides: allocation churn if you mutate in a tight loop (use a builder), and deep immutability requires every nested object to be immutable too.