Skip to content
Tutorials Center
My learning

Topics

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.

C#
public sealed record Address(string Street, string City);

var moved = home with { City = "Oslo" };   // home is unchanged

Try it

C# init, records and with

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.

C# Interior mutability and immutable collections

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

C#
// 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 readonly fields is still mutable if a field holds a List<T>. Use immutable collections, or expose IReadOnlyList<T> over a private copy.
  • ReadOnlyCollection<T> and IReadOnlyList<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.
  • init is not set-once at run time. Reflection can bypass it, and an init accessor can run several times during one object initializer.
  • Records are immutable by convention. Positional records use init properties, but you can declare a record with settable properties; then it is mutable and value equality becomes dangerous as a dictionary key.
  • readonly struct lets the compiler pass the struct by in without copying it defensively. Mark structs readonly unless they must change.
  • Strings, DateTime, Guid, tuples of immutable values and enums are already immutable; ValueTuple itself 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.Add in a loop is slower than building a List<T> once and converting. Use ImmutableArray.CreateBuilder<T>() when building.