skip to content

In .NET, what does each promise when a pricing service hands out flags as a ReadOnlyCollection<T>, an ImmutableList<T> or a FrozenSet<T>?

level: middleimportance: should knowfreq 48%

answer

  1. who can still change it
  2. view versus copy
  3. new version on every change
  4. built once, never changed, fast reads

basics

~20 s

A ReadOnlyCollection<T> is a read-only view: callers cannot change it, but the owner's list still can. An ImmutableList<T> is a copy nobody can change; changes return new versions. A FrozenSet<T> (.NET 8) is also unchangeable, built once for fast lookups.

solid answer

~40 s

They are three different promises. `ReadOnlyCollection<T>` (what `List<T>.AsReadOnly()` returns) only restricts the *caller*: it wraps the owner's list, so when the owner adds an item the view shows it. `ImmutableList<T>` from `System.Collections.Immutable` promises that *nobody* can change that instance; `Add`, `Remove` and `SetItem` return a new list that shares most of its tree with the old one, so it suits data that keeps getting new versions. `FrozenSet<T>` and `FrozenDictionary<TKey,TValue>` (`System.Collections.Frozen`, added in .NET 8) are also unchangeable but have no methods that produce a new version at all: they spend extra time at `ToFrozenSet` to pick a lookup strategy for the actual items, then typically answer `Contains` and `TryGetValue` faster. All three are shallow: the element objects themselves stay as mutable as their types allow.

code

csharp · 23 lines
csharp
using System.Collections.Frozen;
using System.Collections.Immutable;
using System.Collections.ObjectModel;

var flags = new List<string> { "new-checkout", "dark-mode" };

ReadOnlyCollection<string> view = flags.AsReadOnly();      // read-only: a window onto flags
ImmutableList<string> snapshot = flags.ToImmutableList();  // immutable: an independent copy
FrozenSet<string> frozen = flags.ToFrozenSet();            // frozen: a copy built for fast reads

flags.Add("beta-pricing");                                  // the owner changes its list

Console.WriteLine($"view {view.Count}, snapshot {snapshot.Count}, frozen {frozen.Count}");
// view 3, snapshot 2, frozen 2

ImmutableList<string> next = snapshot.Add("beta-pricing");  // a new version; snapshot untouched
Console.WriteLine($"snapshot {snapshot.Count}, next {next.Count}"); // snapshot 2, next 3

var rules = ImmutableList.Create(new Rule { Percent = 10 });
rules[0].Percent = 50;                                       // shallow: the element object is still mutable
Console.WriteLine(rules[0].Percent);                         // 50

class Rule { public int Percent { get; set; } }

go deeper

for a junior

Recall the one-line difference: read-only blocks the caller, immutable means nobody can change it, frozen is immutable and built for fast lookups.

for a middle

Explain that ReadOnlyCollection<T> wraps the live list, that immutable Add returns a new collection, and that freezing analyses the keys up front.

for a senior

Match each to a workload: a frozen table for startup data, immutable snapshots for occasionally edited rules, a read-only view only where the owner's edits should show.

for a principal

Frame it as the contract a type gives to every reader, and point out that all three are shallow, so the element types decide whether shared state is really safe.

## Three words that sound alike In everyday speech *read-only*, *immutable* and *frozen* all mean "you can't change it". In .NET they name three different contracts, and picking the wrong one causes real bugs: a report that changes halfway through rendering, or a lookup table rebuilt on every request. The question to ask of each type is **who can still change the data, and what happens when it needs to change?** | Type | Who can change the contents | How a change happens | Typical use | |---|---|---|---| | `ReadOnlyCollection<T>` | the owner of the wrapped list | the owner edits its `List<T>`; the view shows it | hiding a list from callers | | `ImmutableList<T>`, `ImmutableArray<T>`, `ImmutableDictionary<TKey,TValue>` | nobody | `Add`, `Remove`, `SetItem` return a new collection | snapshots that get new versions | | `FrozenSet<T>`, `FrozenDictionary<TKey,TValue>` (.NET 8) | nobody | build a new one from scratch | lookups built once and read constantly | ## Read-only: a window, not a copy `List<T>.AsReadOnly()` returns a `ReadOnlyCollection<T>` that wraps the same list. It has no `Add` method, and casting it to `IList<T>` and calling `Add` throws `NotSupportedException`. But it is a **view**: the owner keeps its `List<T>`, and every later change shows through. The lesson on read-only interfaces covers how to expose a list this way; the point here is only that read-only restricts the caller, not the data. ## Immutable: a value that never changes The types in `System.Collections.Immutable` promise that an instance never changes after it is created, for anyone, on any thread. A method that looks like a mutation returns a **new collection** and leaves the original intact: - `ImmutableList<T>.Add(item)` returns a new `ImmutableList<T>` with one more element. - `ImmutableDictionary<TKey,TValue>.SetItem(key, value)` returns a new dictionary. - The old instance is still valid and still has its old contents, so a reader holding it sees a consistent **snapshot**. `ImmutableList<T>` is a balanced binary tree (an AVL tree in the source), so a new version shares most of its nodes with the old one and allocates only the nodes along one path. That makes immutable collections a good fit when the data **changes now and then** and many readers need a stable copy: a rules snapshot the pricing service replaces when an admin edits a rule. To pass an immutable collection to code that expects the mutable interfaces, `ImmutableList<T>` also implements `IList<T>`, but its `ICollection<T>.IsReadOnly` returns `true` and `ICollection<T>.Add` throws `NotSupportedException`. ## Frozen: built once, read fast `FrozenDictionary<TKey,TValue>` and `FrozenSet<T>` arrived in .NET 8 in the `System.Collections.Frozen` namespace. They are immutable too, but they are tuned for the opposite trade-off: 1. `ToFrozenDictionary` or `ToFrozenSet` copies the source and analyses the keys (their count, their type, and for ordinal string keys their lengths and distinguishing characters) to choose a specialised implementation. The source comments call this a relatively high cost to create. 2. After that, lookups such as `TryGetValue` and `Contains` are typically faster than on a `Dictionary<TKey,TValue>` or `HashSet<T>`, because the chosen strategy fits those exact keys. 3. There is no `Add`, `Remove` or `SetItem` that returns a new version. Changing the data means building a new frozen collection. So frozen fits data loaded **once at startup** and read on every request, like the currency table, while immutable fits data that gets **new versions** during the process lifetime. ## All three are shallow None of these types freezes the objects inside it. An `ImmutableList<Rule>` whose `Rule` class has a settable `Percent` property still lets anyone write `rules[0].Percent = 50`. The collection's promise is about which elements it holds, not about their state. For truly unchangeable data, the element type must be immutable as well. ## How to choose - Callers only need to look, and the owner keeps editing: a **read-only view**. - Readers need a stable snapshot, and the data changes occasionally: an **immutable** collection, replaced as a whole. - The data is built once and read constantly: a **frozen** collection. In the pricing service, that maps cleanly. The currency table loaded at startup and read on every request becomes a `FrozenDictionary<string, decimal>`. The feature-flag rules, which an admin edits a few times a day, live in an `ImmutableDictionary<string, Rule>` that is replaced as a whole on each edit, so an in-flight request keeps the version it started with. An admin screen that shows the owner's working list, and should reflect its edits, can get a read-only view. One more consequence: a member typed as `IReadOnlyList<T>` or `IReadOnlyDictionary<TKey,TValue>` does not tell the caller which of these promises it is getting, since all three kinds implement those interfaces. When the guarantee matters to callers, typing the member as the concrete immutable or frozen type states it in the signature. The code example shows all three taken from the same `List<string>`, then the owner adding a flag: only the view sees it.

  • Why does ImmutableList<T> implement IList<T> at all if it can never change?
    So it can be passed, for reading, to existing APIs that accept the mutable interfaces. Its `ICollection<T>.IsReadOnly` returns `true`, and the mutating interface members such as `ICollection<T>.Add` throw `NotSupportedException`. Only the public methods that return a new list, like `ImmutableList<T>.Add`, actually work.
  • Can an ImmutableList<T> be shared across threads without locks?
    Reading it can. An instance never changes, so any number of threads can enumerate or index it safely. What still needs care is the *variable* holding the current version: replacing it while others replace it too needs a compare-and-swap such as `ImmutableInterlocked.Update`, or a lock, or updates are lost.
  • Why not just use FrozenDictionary<TKey,TValue> everywhere instead of ImmutableDictionary<TKey,TValue>?
    Because a frozen dictionary has no cheap way to make a new version. Every change means a full `ToFrozenDictionary` build, which analyses all the keys again. When the data changes often, `ImmutableDictionary<TKey,TValue>.SetItem` shares most of the old structure and is far cheaper per change, even though its lookups are slower.

A read-only view is a shop window onto the stockroom: you cannot touch the goods, but the staff can rearrange them behind the glass. An immutable list is a printed catalogue: a change means printing a new edition. A frozen set is a catalogue printed once with a precomputed index, quick to look things up in and never reprinted in place.

  • ReadOnlyCollection<T> is a copy, so the owner's later changes do not show
  • ImmutableList<T>.Add throws because the list cannot change
  • FrozenDictionary is just a Dictionary with a read-only flag set
  • An immutable collection also makes the objects inside it immutable
  • Frozen and immutable collections are interchangeable for frequently edited data

Assumes .NET 10; FrozenSet<T> and FrozenDictionary<TKey,TValue> were added in .NET 8, while System.Collections.Immutable predates them.