C# Reference ยท Classes and Object-Oriented Concepts
Immutable types
Design guide to immutable types in C#: readonly fields, init-only properties, records, readonly structs, with expressions and immutable collections.
An immutable type is one whose instances cannot change after construction. Instead of modifying an object, you create a new one with the changed values. Immutable objects are safe to share between threads, safe to use as dictionary keys, easy to reason about, and need no defensive copies. The price is allocating a new object for every change, which is rarely a problem except in hot loops with large objects.
C# offers several building blocks: readonly fields, get-only and init properties, record types with with expressions, readonly struct, and the System.Collections.Immutable collections.
public sealed record Address(string Street, string City); var moved = home with { City = "Oslo" }; // home is unchanged
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
// readonly field private readonly int _id; // init-only property public string Name { get; init; } // record (positional): init-only properties, value equality, with public record Point(int X, int Y); // readonly struct: every field must be readonly public readonly struct Money { public decimal Amount { get; } } // readonly record struct public readonly record struct Pair(int A, int B);
| Tool | What it protects |
|---|---|
readonly field |
The field can only be assigned in the declaration or constructor. The object it refers to can still change. |
get; only property |
Assignable only in the constructor (or property initializer). |
init accessor |
Assignable in constructors and object initializers, not afterwards. |
required |
Forces callers to set the member during initialization. |
record / with |
Concise immutable data; with copies and changes selected members. |
readonly struct |
The compiler enforces that no member modifies the struct and avoids defensive copies. |
ImmutableArray<T>, ImmutableList<T>, ImmutableDictionary<TKey,TValue> |
Collections whose "mutating" methods return a new collection. |
Usage notes
- Shallow immutability is not enough. A class with only
readonlyfields is still mutable if a field holds aList<T>. Use immutable collections, or exposeIReadOnlyList<T>over a private copy. ReadOnlyCollection<T>andIReadOnlyList<T>are views, not copies. Whoever holds the original list can still change what the view shows.- Copy on the way in. If a constructor receives a mutable collection, copy it (
ToImmutableArray(),ToArray()) so the caller cannot change it afterwards. initis not set-once at run time. Reflection can bypass it, and aninitaccessor can run several times during one object initializer.- Records are immutable by convention. Positional records use
initproperties, but you can declare a record with settable properties; then it is mutable and value equality becomes dangerous as a dictionary key. readonly structlets the compiler pass the struct byinwithout copying it defensively. Mark structsreadonlyunless they must change.- Strings,
DateTime,Guid, tuples of immutable values and enums are already immutable;ValueTupleitself is a mutable struct, so avoid mutating its fields. - Thread safety follows for free. Immutable objects can be read from many threads with no locking. Publishing the reference is the only shared step.
- Performance: many small allocations are cheap in .NET, but repeated
ImmutableList.Addin a loop is slower than building aList<T>once and converting. UseImmutableArray.CreateBuilder<T>()when building.