Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 182 ยท Collections

Immutable, Frozen and Read-only Collections

Learn the difference between read-only views, ImmutableArray, ImmutableList, ImmutableDictionary and FrozenDictionary in C#, with builders, copy-on-change behaviour and when to choose each.

A List<T> can be changed by anyone who holds a reference to it. That is convenient while you build data and dangerous once you share it. If a method returns its internal list, the caller can add, remove or clear items behind your back, and no error tells you who did it. .NET offers three families of tools to protect your data: read-only views that hide the mutating methods, immutable collections that can never change after creation, and frozen collections that are built once and optimized for fast lookups.

They look similar but behave very differently, and mixing them up is a classic source of bugs: a "read-only" list can still change under your feet, while an immutable list cannot. This lesson explains each family with runnable code, shows how the builders work, and ends with a table for choosing between them. It assumes you know List of T and Dictionary.

Read-only interfaces: IReadOnlyList and friends

The simplest protection is a type that does not offer any mutating methods. IReadOnlyList<T> has an indexer and Count, but no Add or Remove. IReadOnlyCollection<T> has just Count, and IReadOnlyDictionary<TKey, TValue> has lookups only. A method that returns IReadOnlyList<T> tells callers "you may read this, not change it".

C# Returning IReadOnlyList

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.

The class keeps full control: only Hire can add people. This is the standard way to expose a collection property. But look carefully at what the property returns: the same list object, just typed through a narrower interface. That has a catch.

A view is not a copy

C# A read-only view still sees later changes

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.

Three lessons in one example:

  1. A read-only view reflects changes made through the original reference. It protects against callers, not against the owner.
  2. Plain interface typing can be defeated with a cast. If you need a guarantee, return list.AsReadOnly(), which returns a ReadOnlyCollection<T> wrapper that offers no way back to the list.
  3. If the data must never change, make a copy (ToArray(), ToList(), [..source]) or use a true immutable collection.

Immutable collections

The System.Collections.Immutable namespace contains collections that never change after they are created. Every "modifying" method returns a new collection and leaves the original untouched. You can pass an immutable collection to any thread without a lock, keep old versions as history, and compare snapshots safely. The namespace is part of the .NET shared framework, so it needs no extra setup in a modern project (in older projects it was a NuGet package).

C# ImmutableArray and ImmutableList

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.

The line original.Add(99); compiles, runs and does nothing useful, because the new array it returns is thrown away. With normal lists, Add mutates; with immutable collections you must use the return value.

ImmutableArray versus ImmutableList

  • ImmutableArray<T> wraps an ordinary array. Reading by index is as fast as an array, memory use is minimal, and iteration is fast. But every Add or Remove copies the whole array, which is O(n).
  • ImmutableList<T> is a balanced tree. Reading by index is O(log n) and slower in practice, but adding, inserting or removing shares most of the old tree, so it costs O(log n) instead of O(n).

Pick ImmutableArray<T> for data that is built once and read many times, which is the usual case. Pick ImmutableList<T> only if you truly make many small changes to a large collection and need to keep earlier versions.

ImmutableArray<T> is a struct. A default(ImmutableArray<int>) is an "uninitialized" value whose Length throws NullReferenceException. Check IsDefault or IsDefaultOrEmpty if a struct field may never have been assigned.

ImmutableDictionary, ImmutableHashSet and friends

The family also contains ImmutableDictionary<TKey, TValue>, ImmutableSortedDictionary, ImmutableHashSet<T>, ImmutableSortedSet<T>, ImmutableQueue<T> and ImmutableStack<T>.

C# ImmutableDictionary keeps old versions

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.

Each version is a separate snapshot. This pattern is ideal for configuration objects, undo history and state that several threads read: nobody can modify a snapshot in the middle of someone else's read.

Builders: efficient batch changes

Calling Add in a loop on an immutable collection creates a new collection each time, which is wasteful. A builder is a mutable twin you fill quickly, then convert once with ToImmutable().

C# Using a builder for bulk work

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.

The LINQ-style helpers ToImmutableArray(), ToImmutableList(), ToImmutableDictionary(keySelector, valueSelector) and ToImmutableHashSet() cover the common case of converting an existing sequence.

Frozen collections: built once, read very fast

FrozenDictionary<TKey, TValue> and FrozenSet<T> (in System.Collections.Frozen, added in .NET 8) are different in goal. They are not about safe sharing during change; they are about fastest possible lookups for data that is created at startup and never modified again, such as a table of file extensions, HTTP status descriptions or reserved keywords.

Creating one is deliberately slow, because it analyses your keys and picks the best lookup strategy for them (for example choosing a specialized hashing scheme for short strings, or a binary search for small integer ranges). After that, TryGetValue and Contains beat a normal Dictionary or HashSet.

C# FrozenDictionary and FrozenSet

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.

There are no Add, Remove or builders. To change the contents you build a new frozen collection from scratch. The comparer you pass is baked in during construction, so choose it carefully: StringComparer.OrdinalIgnoreCase is the common one.

Create frozen collections once, in a static readonly field or at application startup, never inside a method that runs for every request. Building one for a short-lived lookup costs more than it saves. Use them when data is created once and read thousands of times.

Immutability inside your own types

Collections are one part of a bigger idea. You can also make your own objects immutable with init-only properties, readonly fields and records. A record that holds an ImmutableArray<T> is deeply immutable: nothing reachable from it can change.

C# A deeply immutable record

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.

Notice that ImmutableArray<T> compares by reference in record equality, not by contents, so two carts with equal items are not ==. Keep that in mind when you compare records that contain collections of any kind.

Choosing between them

Need Choose
Expose a collection property, owner still mutates internally IReadOnlyList<T> or IReadOnlyDictionary<K,V>
Expose a wrapper that cannot be cast back list.AsReadOnly() (ReadOnlyCollection<T>)
Build once, then read and share across threads ImmutableArray<T>
Many cheap "modified copies" of a large sequence ImmutableList<T>
Shared key-value snapshot that evolves by copy ImmutableDictionary<K,V>
Large lookup table created at startup, read constantly FrozenDictionary<K,V> / FrozenSet<T>
A temporary collection you will keep changing List<T>, Dictionary<K,V> (no protection needed)

Two more notes. First, interfaces are not guarantees: a method that returns IReadOnlyList<T> could be handing out a mutable list. If that matters, return an immutable type or a copy. Second, immutable collections are not free: they allocate on every change and are slower to modify than List<T>. They shine when sharing and safety are worth more than raw write speed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class returns its private List<int> as IReadOnlyList<int>. What can the owner still do?

    IReadOnlyList is a narrower view of the same object. It stops callers from calling Add, but it is not a snapshot.
  2. 2. What does this do: immutableArray.Add(5); (return value ignored)?

    Immutable collections return a new collection from every change. The original is unchanged, so you must use the returned value.
  3. 3. Which type is the best fit for a lookup table built once at startup and read millions of times?

    Frozen collections spend extra time at creation to optimize lookups, then offer the fastest reads.
  4. 4. Why use a builder (ImmutableArray.CreateBuilder) when adding many items?

    Calling Add repeatedly makes a new collection each time. A builder mutates a temporary buffer and calls ToImmutable() once.
  5. 5. What is true about ImmutableArray<T> compared with ImmutableList<T>?

    ImmutableArray wraps an array, so reads are quick and changes copy it. ImmutableList is a balanced tree that shares structure between versions.

Summary

  • A read-only interface or view (IReadOnlyList<T>, AsReadOnly()) hides mutators but still reflects changes made by the owner; it is not a snapshot.
  • Immutable collections (ImmutableArray, ImmutableList, ImmutableDictionary, ...) never change; every "change" returns a new collection, so always use the return value.
  • ImmutableArray<T> is the default choice for read-heavy data; ImmutableList<T> suits many cheap modified copies.
  • Use builders (CreateBuilder, ToImmutable) or ToImmutableArray() for bulk construction.
  • FrozenDictionary and FrozenSet (.NET 8) are expensive to create and fastest to read; build them once and keep them.
  • Immutability makes data safe to share across threads without locks.

Next: IEnumerable, ICollection and IList