Chapter 4: Immutable design
When several methods share mutable data, tracking when and by whom it was changed can take more effort than changing the data itself. Immutable design is one way to reduce these problems.
In traditional object-oriented programming, we often assume that “state changes” are both normal and desirable. However, this flexibility is also a common source of bugs: when an object’s state can be modified by any piece of code at any time, tracking down the root cause of a problem becomes much harder.
Imagine you put a document in a shared company folder and anyone can casually edit a few words. Can you still trust what the document says? That’s the chaos of mutable shared state.
Immutable design flips the default: once an object is created, you don’t modify it. If you need a different state, you create a new object.
This chapter explains how C# supports immutable design: we’ll start with the foundational choice between struct and class, then move on to modern C# features built for immutability, such as record types and init accessors.
4.1 Why immutable design?
Before we dive into syntax, let’s examine what mutable state breaks—and what immutability fixes.
Consider the following seemingly harmless code:
This code has several potential issues:
- Hidden side effects: calling
ProcessPaymentmutates the passed-incustomer, but the method signature doesn’t reveal this behavior. If callers don’t expect that side effect, they may later read data that has already been changed, leading to bugs. - Hard to trace: if
Balanceis wrong, you must search the entire codebase for every place that might mutate it. - Not thread-safe: multiple threads mutating the same object can cause race conditions.
If ProcessPayment returns a new Customer instead of modifying its input, callers can decide which version to retain.
Suppose Alice’s balance is 500. After the payment method returns, the original Customer still has 500, while the new object has 400. Other code holding the original object does not see the change. This illustrates data updates only; real payments also require transaction and amount validation.
Benefits of immutable design
- Predictability: A data version already obtained cannot change through mutation of the same object elsewhere.
- Fewer side effects: A method can return new state, as above. Using immutable objects does not imply every method is free of I/O or other side effects.
- Easier sharing: Once deeply immutable data is safely published to other threads, it can be shared for reading without locks to prevent content changes. Concurrent updates to a variable referencing the latest version still require synchronization.
- Caching and history: Stable objects can be reused. Whether caching or retaining versions is worthwhile depends on the cost.
Additional notes
Strings are immutable, so .NET can reuse certain identical string instances (see System.String.Intern). Configuration can be designed as immutable snapshots, but not all objects in the Options pattern in .NET are immutable.
4.2 Struct vs. class: choosing the right type
In C#, struct and class are the two foundational user-defined types. A struct is a value type; a class is a reference type. Their declarations look similar—both can define properties, methods, and constructors—but their runtime behavior and memory semantics differ significantly. Understanding that difference is the first step to designing good types.
Value types vs. reference types
Chapter 1 introduced the distinction: assigning a struct variable copies its value, while assigning a class variable copies its reference. Both references may refer to the same object. Copying a struct with reference fields does not automatically copy the referenced objects.
When choosing a type, consider whether you want value semantics or shared object identity, not just size and allocation cost.
When should you use struct?
Use struct when:
- It’s a small data structure: Coordinates, RGB colors, time ranges, dictionary keys or key-value pairs, etc.
- It’s immutable: State does not change after creation.
- You don’t need polymorphism: No need for inheritance.
Here’s a typical example:
public readonly struct Money
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency)
{
Amount = amount;
Currency = currency;
}
public Money Add(Money other)
{
if (Currency != other.Currency)
throw new InvalidOperationException(
"Currencies do not match.");
return new Money(Amount + other.Amount, Currency);
}
}This Money struct represents an immutable monetary amount with two core pieces of information: Amount and Currency. This design keeps calculations safe—for example, Add prevents you from accidentally mixing currencies.
Note the readonly struct declaration on line 1: in this Money example, it ensures the struct’s state does not change after construction. Add returns a new Money value instead of mutating the existing one. However, keep in mind that readonly struct only guarantees that its fields cannot be reassigned; if a field refers to a mutable reference type, that still doesn’t imply deep immutability. For example:
readonly struct prevents you from pointing Items at a different List<string>, but it cannot stop you from calling Add on that list. Deep immutability requires immutable collections and immutable elements. Section 4.7 introduces the basics; Section 4.9 covers collection selection.
When should you use class?
A class is usually appropriate for reference semantics, larger data, or class inheritance:
- You need inheritance.
- Instances are large: copying would be expensive.
- You need reference semantics: multiple variables should refer to the same instance.
- You need lifecycle tracking: creation/disposal patterns matter.
Common mistake: mutable struct
Making a struct mutable is a common design mistake. For example:
This is a classic anti-pattern. When you’re accustomed to structs being value types, this mutability can lead to confusing behavior or unexpected consequences, as shown in the following example:
MutablePoint p = new MutablePoint { X = 10, Y = 20 };
p.Move(5, 5); // p becomes (15, 25)
// But...
MutablePoint[] points = new MutablePoint[1];
points[0] = new MutablePoint { X = 10, Y = 20 };
points[0].Move(5, 5); // With arrays, this mutates the element
Console.WriteLine($"{points[0].X}, {points[0].Y}"); // "15, 25"
// And here's an even more confusing case
IList<MutablePoint> list =
new List<MutablePoint> { new MutablePoint { X = 10, Y = 20 } };
list[0].Move(5, 5); // This mutates a temporary copy, which is discarded
Console.WriteLine($"{list[0].X}, {list[0].Y}"); // "10, 20"With arrays, calling a method on an indexed element can mutate the element because the array indexer returns a reference to the element itself. But when you access a generic list through the IList<T> interface, the indexer returns a temporary copy of the struct, so Move mutates that copy while the original element in the list remains unchanged. This is a classic “silent failure” that’s incredibly painful to debug.
Source code: DemoMutablePoint
Here’s another case that often surprises people:
To avoid these issues, structs should almost always be immutable. Use readonly struct to have the compiler enforce that.
readonly struct: compiler-enforced immutability
readonly struct ensures that all fields of the struct are treated as read-only. This not only communicates intent but also enables further compiler optimizations:
If you try to define a mutable field or write to a field inside a readonly struct, the compiler will produce an error. You can also mark specific methods as readonly, which means the method won’t mutate any fields:
Source code: DemoReadonlyStruct
Related Microsoft docs: The
structtype, readonly (C# reference)
At this point, designing a readonly struct looks straightforward. However, there’s still a hidden performance trap: if you don’t understand the compiler’s behavior, you can pay an extra cost without realizing it.
Reading suggestion
Having mastered the semantic differences between
structandclass, the pitfalls of mutable structs, andreadonly struct, you now have the core foundation for designing immutable types. The upcoming discussions on “defensive copies” and “ref struct” cover advanced low-level performance and memory mechanics. If your primary goal is designing immutable data objects, DTOs, or domain models, feel free to skip directly to 4.3 record: simplifying data type definitions. You can always return to these advanced performance topics when tuning high-throughput scenarios or learning how Span works.
ref struct: stack-only structures
A ref struct such as Span<T> has strict lifetime constraints: it cannot be boxed or stored in an ordinary class field, and its value cannot survive an await suspension point. Ordinary immutable data models rarely need it. See Section 13.4 for the full rules and high-performance memory uses.
4.3 record: simplifying data type definitions
Some types exist mainly to store and carry data—for example, DTOs, domain events, and application settings. With these types, we usually care whether their data is the same, not whether two variables refer to the same object. We may also want them to display meaningful contents and make it easy to create a copy with only a few values changed.
With an ordinary class, you often have to implement these features yourself: override Equals, GetHashCode, and ToString, and write additional code for deconstruction or copying. None of these tasks is especially difficult on its own, but together they create a fair amount of repetitive boilerplate.
C# 9 introduced record to simplify the design of these data-centric types. We’ll first look at the basic declaration and the members generated by the compiler, then examine value equality, and finally compare when to use record class and record struct.
record declaration syntax
The syntax for defining a record is concise:
// Primary-constructor syntax
public record Person(string Name, int Age);This form, with parameters written directly after the type name, is called a positional record. From that single line, the compiler generates several useful members based on Name and Age:
- Corresponding
initproperties namedNameandAge(see Section 4.4). - Generated value-equality members such as
Equals,GetHashCode, and the==and!=operators. - Useful
ToString()output, such asPerson { Name = Alice, Age = 30 }. - A
Deconstructmethod for deconstruction. - Compiler-generated members that support
withexpressions (see Section 4.5; the internal mechanism differs slightly betweenrecord classandrecord struct).
What is a primary constructor?
A primary constructor places constructor parameters directly after the type name. The syntax first appeared with records in C# 9 and was later extended to ordinary classes and structs in C# 12.
For an ordinary class or struct, primary-constructor parameters do not automatically become fields or properties. For a positional record, the compiler generates corresponding public properties. That is why the example above can define
NameandAgein one line.
The following example shows several convenient features of records:
// 1. Properties with init accessors
var person = new Person("Alice", 30);
// person.Name = "Bob"; // ✘ Compile error: init-only
// 2. Meaningful ToString
Console.WriteLine(person);
// Output: Person { Name = Alice, Age = 30 }
// 3. Value equality: the same data means the values are equal
var person2 = new Person("Alice", 30);
Console.WriteLine(person == person2); // True (same contents)
// 4. Deconstruct
var (name, age) = person;
Console.WriteLine($"{name} is {age} years old"); // Alice is 30 years old
// 5. with expression support (see Section 4.5)
var olderPerson = person with { Age = 31 };
Console.WriteLine(olderPerson); // Person { Name = Alice, Age = 31 }If you wrote the same behavior with a traditional class, you’d usually end up with many lines of boilerplate code.
Note
The central idea of
recordis language support for data-centric types; a record does not by itself guarantee immutability. ThePersonexample is a positionalrecord class, so the compiler generatesinitproperties forNameandAge. If you instead declare ordinary properties withsetaccessors in the record body, the record can still be mutable.Also,
initprevents a property from being reassigned after initialization. If the property refers to a mutable object, that object’s contents can still change. Section 4.4 examinesinitaccessors in more detail.
Value equality
Of the generated features listed above, value equality deserves a closer look first. The following example shows the behavioral difference between an ordinary class and a record:
// A class uses reference equality by default
class PersonClass
{
public string Name { get; set; }
public int Age { get; set; }
}
var p1 = new PersonClass { Name = "Alice", Age = 30 };
var p2 = new PersonClass { Name = "Alice", Age = 30 };
Console.WriteLine(p1 == p2); // False (different instances)
// A record uses value equality by default
record PersonRecord(string Name, int Age);
var r1 = new PersonRecord("Alice", 30);
var r2 = new PersonRecord("Alice", 30);
Console.WriteLine(r1 == r2); // True (same values)Key differences:
- Default class behavior:
p1 == p2checks whether both references point to the same object. Even ifp1andp2have identical contents, they’re two different instances, so the result isFalse. - Default record behavior: The compiler generates value-equality members such as
Equals,GetHashCode, and==. For thePersonRecord(string Name, int Age)example above, two records are compared using the values ofNameandAge, rather than merely checking whether both variables refer to the same object.
Note
Record value equality is not recursive deep equality. If a member is an array, collection, or another reference type, that member still follows its own equality rules. For example, two separately created arrays with identical elements may still compare as different values by default.
To customize record equality, define Equals(PersonRecord? other) (it must be virtual for an unsealed record class). Override GetHashCode() consistently: equal objects must have equal hash codes for hash-collection lookups to work.
Source code: DemoRecord
For data-centric types, record equality often matches the requirement more closely: whether two instances are equal depends on the equality rules of their data members, not on object identity.
That makes records a good fit for:
- DTOs (data transfer objects): to move data across layers
- Domain events: to represent something that happened in the system
- Configuration types: application settings
A complete example of manual value equality
To compare ordinary Person instances consistently through Equals, ==, and hash-based collections, implement the following members. This is optional advanced reading; if you only need records, skip to the next subsection.
- Implement
IEquatable<T>: Provides strongly typed Equals; for value types it can also avoid boxing. - Override
Object.Equals(object? obj): Maintains consistent equality results when instances are compared throughobjectreferences. - Override
Object.GetHashCode(): Ensures equal objects have equal hash codes. - Overload
==and!=: Keeps operators consistent with Equals.
We use a sealed class to exclude derived-type equality rules. IEquatable is a generic interface defining equality between values of the same type; Chapter 7 covers generics.
public sealed class Person : IEquatable<Person>
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age) => (Name, Age) = (name, age);
// 1. Strongly typed IEquatable<T>
public bool Equals(Person? other) =>
other is not null && (ReferenceEquals(this, other) || (
Name == other.Name && Age == other.Age));
// 2. Override Object.Equals
public override bool Equals(object? obj) => Equals(obj as Person);
// 3. Override GetHashCode (must be consistent with Equals)
public override int GetHashCode() => HashCode.Combine(Name, Age);
// 4. Operator overloads
public static bool operator ==(Person? left, Person? right) =>
left is null ? right is null : left.Equals(right);
public static bool operator !=(Person? left, Person? right) =>
!(left == right);
}Equal objects must have equal hash codes, but unequal objects may share a hash code. Changing equality-relevant state after using an object as a key can affect lookups. For simple data types, record Person(string Name, int Age); avoids this manual implementation.
Source code: DemoEquality
record class vs. record struct
The earlier Person example uses the most common form, record class. Starting with C# 10, you can also declare a record as the value type record struct. This lets you choose based on data size, copying cost, and how the type will be used:
// record class (default; same as writing record)
public record class PersonRecord(string Name, int Age);
// record struct (a value-type record)
public record struct Point(int X, int Y);
// readonly record struct (prevents fields and properties from being
// reassigned)
public readonly record struct ImmutablePoint(int X, int Y);record class is the default. When you write record MyRecord, you’re effectively declaring a record class.
With positional record class syntax, primary-constructor parameters generate init-only properties by default. They can be set during initialization but cannot be reassigned afterward:
With positional record struct syntax, primary-constructor parameters generate read-write properties by default, so they can be reassigned after construction:
If you want to prevent those positional properties from being reassigned after initialization, use readonly record struct:
readonly prevents fields and properties from being reassigned. If a member refers to a mutable object, that object’s contents can still change.
When should you use record class?
record class is a reference type and is a good fit when you want to:
1. Define DTOs: pass data across layers or services
public record class UserDto(int Id, string Email, string DisplayName);2. Model domain events: represent important events in the system
public record class OrderPlacedEvent(int OrderId, DateTime PlacedAt,
decimal Total);3. Represent larger data shapes: many properties or nested structures where copying would be expensive
Because it’s a reference type, multiple variables can point to the same instance. When you use init-only properties and avoid exposing mutable internal objects, it works well for passing and sharing data throughout an application.
When should you use record struct?
record struct is a value type, so its use cases are largely the same as struct. For example:
// Small, independent value objects, such as coordinates or colors
public readonly record struct Point(int X, int Y);
public readonly record struct ColorRgb(byte R, byte G, byte B);
// Avoiding heap allocation: high-performance calculations or
// frequently created/collected values
public readonly record struct TimeRange(DateTime Start, DateTime End);
// Dictionary keys: use as a composite key
public readonly record struct CacheKey(string UserId, string Resource);
var cache = new Dictionary<CacheKey, string>();Selection guidelines
Choosing record class vs. record struct follows the same general guidance as choosing class vs. struct:
- Most of the time: use
record classunless you have a specific performance reason. - Small value objects: consider
readonly record struct. - When unsure: start with
record classand optimize only when profiling proves it’s needed.
The following table summarizes key differences between class, struct, record class (i.e., record), and record struct:
| Feature | class | struct | record class | record struct |
|---|---|---|---|---|
| Type category | Reference type | Value type | Reference type | Value type |
| Inheritance | ✔ Supports inheritance | ✘ No inheritance (can implement interfaces) | ✔ Supports inheritance | ✘ No inheritance (can implement interfaces) |
| Default equality | Reference equality | Value equality (Equals/GetHashCode) |
Value equality (generated) | Value equality (generated) |
| Mutability | Depends on member declarations | Mutable by default (prefer readonly struct) |
Depends on member declarations; positional properties are init-only by default | Depends on member declarations; positional properties are read-write by default |
| ToString() | Type name by default | Type name by default | Generated (prints data member names and values) | Generated (prints data member names and values) |
with support |
No (manual) | ✔ Yes (C# 10+) | ✔ Yes (generated) | ✔ Yes (generated) |
| Deconstruction | Manual Deconstruct needed |
Manual Deconstruct needed |
Generated for positional declarations | Generated for positional declarations |
| Typical use | Inheritance, larger objects, reference semantics | Small data, performance, avoid heap allocation | DTOs, domain events, configuration, immutable data | Small value objects, composite keys |
4.4 init accessors: preventing reassignment after initialization
Before C# 9, if you wanted to prevent callers from reassigning properties after an object was created, the usual approach was get-only properties assigned in the constructor. However, this meant sacrificing the convenience of object initializers (introduced back in C# 3.0). You had to choose between restricting reassignment and using initializer syntax.
C# 9’s init accessors solve that by letting you set properties only during initialization. You can keep object initializer syntax while preventing those properties from being reassigned later. This restriction helps with immutable design, but it does not make an object deeply immutable when a property refers to a mutable object.
init accessor syntax
Compare the traditional approach with an init accessor:
This prevents those properties from being reassigned after construction, but you lose object initializer convenience—and constructor parameter lists can get unwieldy when there are many properties.
With init accessors:
public class Person
{
public string Name { get; init; } = "";
public int Age { get; init; }
}
// Object initializer is allowed; properties cannot be reassigned
// afterward
var person = new Person { Name = "Alice", Age = 30 };
// Later assignment to an init-only property fails at compile time
person.Name = "Bob"; // ✘ Compile error: init-onlyinit combines two goals: preventing property reassignment and retaining object initializer syntax.
You keep the flexibility of object initializers (set only what you need, in any order) while preventing those properties from being reassigned after initialization.
However, init has a small gap: it cannot force callers to set certain properties. If a caller omits Name, the object is still created, with the property retaining its default value (an empty string for Name above). The required modifier introduced in C# 11 fills exactly this gap.
Using the required modifier (C# 11)
C# 11 introduced the required modifier to force callers to provide certain properties during initialization:
required ensures that callers must initialize those required members when creating the object, which helps prevent a “missing entirely” kind of half-initialized state (for example, creating a Person and forgetting to provide Name at all).
However, be careful: required guarantees “must be initialized,” not “must be non-null.” If the member type is a non-nullable reference type, the compiler will typically report nullable warnings; if you need to strictly reject invalid values, you should still add appropriate validation logic.
Combining required and init gives you a practical balance: language-level checks during initialization, plus the convenience of object initializers.
Source code: DemoInitAccessor
4.5 with expressions: nondestructive mutation
With immutable design, you do not modify an existing object directly. Instead, you use it as the basis for a copy with selected values changed. A with expression provides concise syntax for this “copy and change” operation.
Here’s the basic idea:
public record Person(string Name, int Age);
var alice = new Person("Alice", 30);
// Use a with expression to create a new instance with specific changes
var olderAlice = alice with { Age = 31 };
Console.WriteLine(alice); // Person { Name = Alice, Age = 30 }
Console.WriteLine(olderAlice); // Person { Name = Alice, Age = 31 }A with expression works as follows: “create a copy, then set certain members on the copy.” The operation does not modify the original object, but it still provides convenient mutation-like syntax.
This pattern is often called nondestructive mutation: rather than changing the original object, you create a new version.
Modifying multiple properties
You can update multiple members in a single with expression:
var bob = alice with { Name = "Bob", Age = 25 };The syntax is intuitive: “Give me a copy of alice, but with these fields replaced.”
How with works under the hood
Under the hood, a with expression involves two key phases:
- Copy phase:
record class: The compiler creates a copy via a synthesized copy constructor. This is a field-level shallow copy (including private and hidden backing fields) that bypassesinitaccessors to ensure the full internal state is preserved.record struct/ ordinarystruct: Performs a direct value copy without calling a copy constructor.
- Update phase: Invokes the
initor setter accessors for the members specified in the braces to apply the new values. Therefore, modified properties still run their validation logic; unspecified members directly retain their values from the copy phase.
The two-stage model retains unspecified members’ original values and runs accessor validation for specified properties. Copying still has a cost; custom copy constructors may change how it is done.
Note: Shallow copy warning
withcopies the object itself. If a member references an external mutable object (such as an array or a standardList), both the old and new instances still point to the same collection, and modifying the collection’s contents will affect both.
What about non-record types?
with isn’t limited to record types: ordinary struct types also support with. For ordinary classes, however, with is not supported. A copy constructor or Clone method by itself does not enable with; if you need similar behavior, you must provide your own copying API and call it explicitly. Also note that record struct and ordinary struct both rely on ordinary value copying, not the hidden clone/copy-constructor machinery used for record class.
public class Person
{
public string Name { get; init; } = "";
public int Age { get; init; }
public Person() { }
protected Person(Person original)
{
Name = original.Name;
Age = original.Age;
}
public Person Copy(string? name = null, int? age = null)
{
return new Person(this)
{
Name = name ?? Name,
Age = age ?? Age
};
}
}
var alice = new Person { Name = "Alice", Age = 30 };
var bob = alice.Copy(name: "Bob");Source code: DemoWithExpression
4.6 Derived properties and lazy evaluation
Immutable types often include derived (calculated) properties—values computed from other members. A common technique is lazy evaluation, deferring computation until the value is actually needed; when calculation is expensive, it is often paired with caching (memoization) for subsequent reads.
Here’s a simple derived property:
Start with this simple implementation. Consider caching only when measurements show that repeated computation is costly enough to justify the added state and complexity.
Lazy evaluation with caching
If calculation is expensive, store the first result in a field and reuse it on subsequent reads. Start with a version that does not address equality, named UncorrectedPoint to distinguish it from the corrected type.
The coordinates have not changed, but the points are no longer equal. Synthesized record equality compares instance fields, including the private _distanceCache. Caching can also change the hash code and break lookups in a HashSet or dictionary.
Fix this by basing equality only on X and Y, which represent the point’s position, and excluding the cache.
public sealed record Point(double X, double Y)
{
private double? _distanceCache;
public bool Equals(Point? other) =>
other is not null && X.Equals(other.X) && Y.Equals(other.Y);
public override int GetHashCode() => HashCode.Combine(X, Y);
public double DistanceFromOrigin
{
get
{
if (_distanceCache == null)
{
_distanceCache = Math.Sqrt(X * X + Y * Y);
}
return _distanceCache.Value;
}
}
}Sealing the record simplifies this equality implementation. Reading the calculated property of only one point no longer affects equality between points with identical coordinates, and the cache does not affect their hash codes.
You can make the getter even more concise with the null-coalescing assignment operator (??=):
public double DistanceFromOrigin => _distanceCache ??= Math.Sqrt(
X * X + Y * Y);This means: if _distanceCache is null, compute and assign it; otherwise return the cached value.
Operator evaluation order
The evaluation order of
_distanceCache ??= expressionis:
- Check whether
_distanceCacheis null.- If it is null, evaluate the right-hand
expressionand assign it to_distanceCache.- Return the value of
_distanceCache(either the existing value or the newly computed one).This syntax is concise, but it is not an atomic operation in the multithreading sense, and it does not by itself provide thread-safe lazy initialization. Two threads could both observe
null, each compute the value independently, and both write their result—resulting in duplicate computation. Even a computation without side effects is not sufficient to establish thread safety:double?is a struct, its reads and writes are not necessarily atomic, and visibility of updates to other threads also matters. The examples here assume single-threaded use. For a shared cache, use the same lock for reads and writes, or a thread-safe configuration ofLazy<T>, and manage the cache lifetime when copying or updating data.For a deeper explanation of
??=, see Chapter 3.
Handling cache invalidation: keeping nondestructive mutation correct
Even after fixing equality, another issue remains: with copies private fields by default. Using the earlier UncorrectedPoint after reading its distance, we can observe:
The new coordinates are (3, 5), so the distance should be √34 (about 5.83), but the copy retains the old cached value 5. This is separate from equality: even custom Equals and GetHashCode do not prevent the default copy from retaining stale cache data.
The diagram shows the incorrect cache copy and the result after using a custom copy constructor.
In a record class, the cleanest solution is a custom copy constructor that deliberately leaves the private cache field out of the copy, forcing the new object to recompute on first access:
public sealed record Point(double X, double Y)
{
private double? _distanceCache;
public bool Equals(Point? other) =>
other is not null && X.Equals(other.X) && Y.Equals(other.Y);
public override int GetHashCode() => HashCode.Combine(X, Y);
public double DistanceFromOrigin =>
_distanceCache ??= Math.Sqrt(X * X + Y * Y);
// Custom copy constructor: copy only X and Y, leaving
// _distanceCache as null
private Point(Point other) => (X, Y) = other;
}
var p1 = new Point(3, 4);
Console.WriteLine(p1.DistanceFromOrigin); // 5 (computed and cached)
var p2 = p1 with { Y = 5 };
Console.WriteLine(p2.DistanceFromOrigin); // 5.83... (cache recomputed)Source code: DemoLazyEvaluation
Advanced tip: precise invalidation using init accessors
A drawback of the copy-constructor approach is that every with expression resets the cache, even when modifying properties unrelated to the calculation. For more precise cache invalidation, you can use the C# 14 field keyword to explicitly set _distanceCache = null inside the init accessors of relevant properties, invalidating the cache only when crucial members change.
Design principle
A private cache preserves logical immutability only when it does not change observable logical state, including equality and hashing. Handle copying and synchronization as well. When the calculation is cheap, computing it directly may be the better choice.
4.7 Practical application: an immutable domain model
Records, init, and with help us create immutable data types, but are not enough when those types contain mutable collections. Let’s first understand immutable collections, then apply them to an order model.
The problem with mutable collections
Even if you mark a mutable collection (like List<T>) as readonly, or expose it as IReadOnlyList<T>, the underlying data can still be modified (for example, by casting it back to List<T>). Consider:
class NumberStore
{
private readonly List<int> _numbers = new List<int> { 1, 2, 3 };
public void Demo()
{
// Still mutable! readonly protects the field reference, not
// the contents
_numbers.Add(4);
IReadOnlyList<int> readOnlyView = _numbers;
((List<int>)readOnlyView).Add(5); // Can still mutate via cast
}
}In this example, readonly simply ensures that the field _numbers cannot be reassigned to a different List<int> after initialization. It does nothing to prevent someone from changing the elements inside that list.
System.Collections.Immutable
.NET provides the System.Collections.Immutable package, which contains truly immutable collection types such as ImmutableList<T> and ImmutableDictionary<TKey, TValue>.
The key principle is: Update operations return the resulting collection version without changing the original. When contents do not change, the implementation may reuse the original instance.
It’s like taking a photo (a snapshot). The landscape can change, but the photo stays the same. If you want a new view, you take a new photo.
Example:
Neither the count nor the contents of list1 change. The elements here are ints; storing mutable objects in an immutable collection does not make those objects immutable.
An immutable order model
Suppose we’re building an order system and use records to define an immutable order:
using System.Collections.Immutable;
// Use a record to define an immutable order item
public record OrderItem(string ProductName, int Quantity,
decimal UnitPrice)
{
public decimal TotalPrice => Quantity * UnitPrice;
}
// Use a record to define an immutable order
public record Order(
int OrderId,
string CustomerName,
ImmutableList<OrderItem> Items,
DateTime CreatedAt)
{
public decimal TotalAmount => Items.Sum(item => item.TotalPrice);
// Use a with expression to "modify" the order
public Order AddItem(OrderItem item)
{
return this with { Items = Items.Add(item) };
}
}Items.Add(item) returns a collection containing the added item, and with creates a new order. Neither the original order nor its collection is modified. Items.Sum(item => item.TotalPrice) adds up all item totals; later chapters explain Sum and lambdas. Section 4.9 compares collection costs.
Next, let’s see how to use this immutable order model:
using System.Collections.Immutable;
var order = new Order(
OrderId: 1,
CustomerName: "Alice",
Items: ImmutableList.Create(
new OrderItem("Keyboard", 1, 2500)),
CreatedAt: DateTime.Now
);
// "Modify" the order (this actually creates a new order object)
var updatedOrder = order.AddItem(new OrderItem("Mouse", 2, 800));
// 2500
Console.WriteLine($"Original order total: {order.TotalAmount}");
// 4100
Console.WriteLine($"Updated order total: {updatedOrder.TotalAmount}");In this example, we never mutate an existing object. Instead, we create a new object to represent each new state. Because Items also uses a truly immutable collection, the original order cannot be changed later through some external reference to the collection.
Benefits of this design:
- History tracking: Retain old and new versions as a basis for undo and redo.
- Easier sharing: Share this immutable order once safely published; concurrent updates to the current order reference still need synchronization.
- Predictability: AddItem does not mutate the original order, making before-and-after results easy to compare.
Source code: DemoOrderModel
Closed state modeling: Union Types (C# 15)
Suppose an order has three payment methods: cash, credit card, and bank transfer. All require an amount, but only credit card payments need a card number, and only bank transfers need an account number.
One traditional approach puts all possible fields in one type:
This type allows a credit card payment without a card number:
Both card and account numbers can also be supplied at once. You must separately validate the combination of payment kind and fields.
Another option derives three payment types from an abstract base class. This separates fields for each case, but an ordinary open hierarchy does not restrict derived types to those three.
C# 15 introduces native union types to address this modeling pain point with concise syntax:
// (1) Define immutable carriers for each mutually exclusive state
public sealed record class Cash(decimal Amount);
public sealed record class CreditCard(string CardNumber, decimal Amount);
public sealed record class BankTransfer(string AccountNo, decimal Amount);
// (2) Use the C# 15 union keyword to declare a closed payment method
public union PaymentMethod(Cash, CreditCard, BankTransfer);- Each state is an independent immutable record containing only the data that payment method needs.
union PaymentMethod(...)declares a wrapper struct that holds a value of one of the listed case types, without requiring a shared base class. The case types aresealedhere to prevent additional payment methods from being introduced through inheritance.
Callers can implicitly convert member types directly into the union type:
Unlike the single Payment type, constructing CreditCard requires a card number and amount, while Cash has no card-number field. This reduces invalid field combinations, but business validation of card numbers, amounts, and other data remains necessary.
A type like OrderItem that combines multiple members is a product type: its possible values are combinations of possible member values. PaymentMethod represents one of a fixed set of case types, a sum type design, also known as a discriminated union. C# unions also permit empty contents.

Source code: DemoUnionTypes
Wrapper structs, default values, and immutability
A union declaration produces an ordinary struct, not a record; it does not synthesize record-style ==, !=, or Deconstruct members. It stores its contents in a single object? field and exposes a get-only Value property. Value-type cases are boxed on entry. Wrapping a mutable case value does not make its contents immutable.
A union can also have no content:
The three-payment-method model assumes normal construction with non-null contents. A default(PaymentMethod), including an element of a newly allocated array, can contain null; handle it with a null arm when accepting such inputs. If a case type is not sealed, its derived instances are also accepted and matched by the corresponding base-type pattern. C# unions distinguish types as cases; defining a separate type for each state gives this example its discriminated-union model.
When to use inheritance or union types
In immutable architectural design, deciding between class inheritance hierarchies and union types depends on the openness of your domain states:
- Use object-oriented inheritance (Open Hierarchy): When your system is open-ended, expecting future modules or external packages to extend with new subtypes (e.g., a graphics library with a base
Shapeclass, where third parties can addTriangle). - Use union types (a closed set of case types): When states are closed and fixed by business rules (e.g., order payment methods, or
SuccessandFailureresults of a network request). The set of case types is fixed; seal the cases too if inheritance must not introduce additional concrete states.
Looking ahead: powerful synergy with pattern matching
Beyond making domain models more precise, the greatest value of union types lies in their synergy with pattern matching: when using a
switchexpression on aPaymentMethod, the compiler knows all possible cases and provides compile-time exhaustiveness checking, eliminating the need for arbitrary_ => throwfallback arms! We will explore this in depth in Chapter 6: Pattern Matching.
Round-tripping payment methods through JSON (.NET 11)
This optional advanced section is for readers storing domain models or transferring them through APIs. A JSON contract defines how data is written and restored; attributes annotate types or members to guide the serializer.
.NET 11 adds System.Text.Json support for union types. It serializes the contained case directly, without a Value wrapper. Our three payment cases are all JSON objects, so the default token-based classifier cannot distinguish them. Use a structural classifier based on property names:
using System.Text.Json;
using System.Text.Json.Serialization;
PaymentMethod method = new CreditCard("TEST-0001", 1200m);
string json = JsonSerializer.Serialize(method);
Console.WriteLine(json);
// {"CardNumber":"TEST-0001","Amount":1200}
PaymentMethod copy = JsonSerializer.Deserialize<PaymentMethod>(json);
Console.WriteLine(copy is CreditCard); // True
[JsonUnion(
TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union PaymentMethod(Cash, CreditCard, BankTransfer);
public sealed record Cash(decimal Amount);
public sealed record CreditCard(
[property: JsonRequired] string CardNumber, decimal Amount);
public sealed record BankTransfer(
[property: JsonRequired] string AccountNo, decimal Amount);CardNumber and AccountNo distinguish the card and transfer shapes from Cash, which has only Amount. JsonRequired requires the property to be present; it does not validate that the string is nonempty. In a top-level program, executable statements precede type declarations, as shown here.
The classifier uses property names and required-property information, not nested values. Ambiguous input throws JsonException; indistinguishable contracts can cause NotSupportedException when the classifier is created. Test older JSON whenever you add a case or rename a property. A default union serializes as null and deserializes back to the default value.
For a closed inheritance hierarchy, [JsonPolymorphic(InferClosedTypePolymorphism = true)] is an alternative that uses a $type discriminator. Declaring a hierarchy closed alone does not enable JSON polymorphism.
Source code: DemoUnionJson
AI-assisted development: refactor toward immutability
The example above showed how to design an immutable model from scratch. In practice, though, you’re more likely to turn existing classes into immutable ones. This kind of refactoring involves type choices, initialization style, and API design, so it’s a good place to ask AI tools to help structure your refactoring approach:
Prompt
Refactor the core data objects in this project into immutable types. Requirements:
- Use
recordorreadonly struct(choose appropriately)- Use
initaccessors- Provide an API that works well with
withexpressions- Explain the reasoning behind your design choices
4.8 The cost of manual value equality
See the complete example in Section 4.3 under value equality. If default record equality meets your needs, no manual implementation is necessary. For custom comparisons, verify that all equality-related members agree.
4.9 Immutable collections
Section 4.7 introduced immutable collections and how they differ from read-only interfaces. Here we compare implementations and costs to help choose a type based on read and write patterns.
Performance considerations
An updated ImmutableList shares unchanged tree nodes with its earlier version, a technique called structural sharing. Implementations differ: adding elements to ImmutableArray generally requires copying the array.

Even so, write-heavy workloads are typically more expensive than with mutable collections. If you need to perform many updates (for example, building a list in a loop), use the builder pattern:
Builders reduce intermediate allocations during bulk updates and let you freeze the result into an immutable collection at the end.
How builders work
A builder offers a mutable interface and may reuse internal storage during construction, reducing intermediate allocations. The collection returned by ToImmutable does not change when the builder is modified later. The actual optimization depends on the type and operation.
ImmutableArray<T> vs. ImmutableList<T>
Another common option is ImmutableArray<T>. It wraps an array, which usually favors indexed access and sequential enumeration; actual memory use and speed depend on the data and operations.
- ImmutableArray: Great read performance (\(O(1)\), contiguous memory), but operations that change contents, such as adding elements, usually create a new array (\(O(N)\)). Best for “build once, read many.”
- ImmutableList: Tree-based with structural sharing.
Addand removal by index withRemoveAttake \(O(\log N)\). Removal by value withRemove(value)first searches for the element, so its worst-case cost is \(O(N)\), assuming each equality comparison takes \(O(1)\). Indexed access takes \(O(\log N)\), and full enumeration takes \(O(N)\). Better when you need frequent updates while keeping immutable semantics.
So if your collection is mostly read-only after construction, prefer ImmutableArray<T>.
Source code: DemoImmutableCollections
Beyond the immutable collections provided by System.Collections.Immutable, if your scenario is “build once, then only read—never modify,” .NET 8+ offers another set of options.
FrozenDictionary and FrozenSet
.NET 8 introduced the System.Collections.Frozen namespace, which includes FrozenDictionary<TKey, TValue> and FrozenSet<T>.
These types have different goals from the immutable collections above:
ImmutableDictionary: Supports nondestructive updates, returning the resulting version. It fits scenarios that retain versions or continue updating after construction.FrozenDictionary: Completely frozen after creation — no mutations whatsoever. It is optimized for frequent lookups but has a higher upfront construction cost. Measure its benefit over a regularDictionaryusing your data and access patterns. It is suited for “build once at startup, read many times” scenarios such as configuration lookup tables and keyword maps.
FrozenSet<T> is the read-optimized counterpart to ImmutableHashSet<T>, similarly tuned for lookup performance.
Example:
In summary, the right collection depends on your usage pattern: for frequent modifications with version history, use ImmutableList or ImmutableDictionary; for mostly-read data with occasional modifications, use ImmutableArray; for data that is only queried after construction, use FrozenDictionary or FrozenSet.
Summary
- .NET 11 can round-trip union cases through JSON; choose a classifier that can distinguish their contracts.
- Immutable design reduces mutation, making code more predictable, safer, and easier to maintain.
structvs.class: Structs are value types and work best for small, immutable data; classes are reference types and work best for larger models and inheritance.readonly structlets the compiler enforce read-only data members and helps avoid defensive copies caused by instance members that aren’t correctly markedreadonly.ref structhas strict lifetime constraints, cannot escape to the managed heap, and enables high-performance APIs likeSpan<T>.- Records are data-centric types with compiler-generated value equality,
ToString, andwithsupport, but records do not by themselves guarantee immutability; you can chooserecord classorrecord struct. initaccessors make properties settable only during initialization; combined withrequired, they require member initialization, but the supplied values still need validation.withexpressions provide nondestructive mutation by creating a new instance.- Derived properties + lazy evaluation can improve performance while preserving logical immutability if caching does not affect observable logical state, including equality and hashing, and copying and synchronization are handled correctly.
- Equality: understand reference equality vs. value equality, and implement
GetHashCodeconsistently (or just use records). - Immutable collections:
System.Collections.Immutablepreserves collection immutability, but deep immutability requires immutable elements too. Consider builders for bulk updates, orFrozenDictionaryorFrozenSetfor lookup-only workloads after construction; measure actual benefits. - Union types (C# 15): A fixed set of case types for state modeling; immutable, sealed case types let the model express immutable domain states.
C# is no longer limited to traditional getters and setters. From readonly struct to records, init accessors, and union, modern C# makes immutable design much easier to apply.
When designing a new type, consider making “immutable by default” your starting point. Spending less time chasing “who changed my data?” leaves more time for work that actually matters.
Glossary
| Term | Description |
|---|---|
| Copy constructor | A special constructor used to copy an existing instance; record class can have one synthesized by the compiler as part of cloning. |
| Deep copy | A recursive copy that duplicates nested objects and collections rather than sharing references. |
| Discriminated union | A data structure that holds a value of one of several possible types, tagged with an identifier. |
| Hash code | A numeric value used by hash-based collections (like Dictionary/HashSet) for fast lookup. |
| Immutable | An object whose logical state cannot be changed after creation. |
| Immutable collection | A collection that never changes; updates return the resulting version without changing the original (for example ImmutableList<T>). |
init accessor |
A property accessor that can be set only during initialization. |
| Lazy evaluation | Defer computation until the value is actually needed; in property implementations, often paired with caching to avoid recomputation. |
| Logical immutability | A pattern where the logical state is immutable, even if internal caches are updated for performance. |
| Primary constructor | Constructor parameter syntax declared with the type, available across the type body. |
| Product type | A composite type formed by combining multiple attributes simultaneously (such as a class or record). |
readonly struct |
A struct declaration that enforces non-mutation of instance fields. |
| Record | A data-centric type introduced in C# 9 with generated value equality; it does not by itself guarantee immutability. |
ref struct |
A struct type with strict lifetime constraints that cannot escape to the managed heap used for high-performance scenarios (for example Span<T>). |
| Reference equality | Equality based on whether two variables refer to the same instance. |
| Reference type | A type whose variables hold references to objects (for example class). |
required modifier |
A modifier that forces callers to initialize required members during object initialization. |
| Shallow copy | A copy that duplicates top-level fields but continues to share referenced sub-objects. |
| Structural equality | Equality based on comparing an object’s members (structure/contents). |
| Structural sharing | An immutable-collection technique that reuses internal nodes between versions to reduce copying. |
| Sum type | A type whose state space is the sum of its possible variants, representing mutually exclusive alternatives (such as a union). |
| Union type | A C# 15 feature allowing the declaration of a closed set of mutually exclusive types. |
| Value equality | Equality based on comparing member values rather than references. |
| Value type | A type whose variables contain the data directly (for example struct). |
with expression |
Syntax that creates a copy from an existing instance and assigns new values to selected members. |
