الانتقال إلى المحتوى
.NETC#· 6 دقائق للقراءة

What readonly and IReadOnlyList Really Protect, and What They Leave Open

readonly freezes a variable and IReadOnlyList hides a few methods. Neither stops the data from changing under you.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

An exchange-rate cache passed code review easily: private readonly List<Rate> _rates, exposed as IReadOnlyList<Rate> Rates => _rates. Two layers of "read-only" protection. A background job refreshes the rates every minute with _rates.Clear() and _rates.AddRange(fresh). Checkout requests that read Rates during a refresh occasionally fail with InvalidOperationException, and once in a while an order is priced while the list is empty. No caller ever wrote to the list. It changed underneath them.

The common misconception

The belief: mark a field readonly, expose it as IReadOnlyList<T>, and the data behind it can never change. Both keywords say "read-only," and the compiler visibly backs them up. Assigning _rates = new() outside the constructor is an error, and Rates.Add(...) doesn't compile because the interface has no Add.

That's why it feels safe: the compiler really does block something. It's a half-truth. Each feature protects one specific thing, and neither of those things is the data. The protection is on the variable and on one particular way of looking at the list, not on the list.

What actually happens

readonly freezes the variable, not the object

A field of a class type holds a reference. Marking it readonly means that after the constructor finishes, the field must keep referring to the same object. Microsoft's reference says it plainly: the modifier doesn't prevent the instance data from being modified through the read-only field. So _rates.Clear() compiles in any method, because it changes the list, not the field.

IReadOnlyList is a view, not a promise

IReadOnlyList<T> is an interface with three things: Count, an indexer, and enumeration. The docs describe a list whose number and order of elements is read-only, and add that the content of the elements isn't guaranteed to be read-only. It says nothing about who else holds the object. List<T> implements it, so Rates => _rates hands every caller a of the live list, and the owner keeps changing it.

C# Program.cs
List<string> roles = ["reader"];IReadOnlyList<string> view = roles;roles.Add("admin");             // the owner keeps writingConsole.WriteLine(view.Count);  // 2: the read-only list changed((List<string>)view).Clear();   // a cast unlocks it completelyConsole.WriteLine(roles.Count); // 0

The view shows every change its owner makes, and a cast hands the caller the real list: it compiles and succeeds at runtime. The elements are only as safe as their type, too: if Rate had a settable Value, cache.Rates[0].Value = 0 would compile without any cast.

ReadOnlyCollection blocks the cast, not the changes

Returning _rates.AsReadOnly() wraps the list in a ReadOnlyCollection<T>, so the cast to List<Rate> fails at runtime. But it's still a wrapper: the docs note that if the underlying collection changes, the read-only collection reflects those changes. Readers still watch a moving list.

Immutable and frozen collections are the real promise

means the data itself can't change once created. ImmutableArray<T> and ImmutableList<T> in System.Collections.Immutable work that way: Add returns a new collection and leaves the original untouched, so anyone can share or cache one without copying it. FrozenSet<T> and FrozenDictionary<TKey, TValue>, added in .NET 8, are immutable too, and are optimized for fast lookups at the cost of a slower build, which suits data created once at startup.

The rate cache, before and after

The same cache, first with "read-only" labels, then with a real snapshot:

C# RateCache.cs
public sealed class RateCache{    private readonly List<Rate> _rates = [];    // Looks read-only to callers, but it is the live list    public IReadOnlyList<Rate> Rates => _rates;    public void Refresh(IEnumerable<Rate> fresh)    {        _rates.Clear();         // compiles: readonly guards the field only        _rates.AddRange(fresh); // a reader may see an empty list right now    }}

Notice that the fixed field is no longer readonly, and the class is safer anyway. The guarantee moved from the variable to the data: Refresh builds a complete new array and swaps the field to it. A request that already read Rates keeps enumerating the old snapshot, which can never change, so it never sees a half-filled list. And because Rate is a positional record, record Rate(string Currency, decimal Value), its properties are init-only, so the elements can't be edited either.

What each tool protects

ToolWhat it protectsWhat it leaves open
readonly fieldWhich object the field refers to, after the constructorEverything inside that object
IReadOnlyList<T>Adding and removing through this interfaceThe owner, a cast, and mutable elements
ReadOnlyCollection<T>The cast back to List<T>Changes made to the wrapped list
ImmutableArray<T>, ImmutableList<T>The contents, for the collection's whole lifeMutable objects stored inside
FrozenSet<T>, FrozenDictionary<TKey, TValue>The contents, with fast lookupsMutable objects stored inside, plus a slower build

How to apply it in your project

  1. Find the leaky propertiesSearch for properties that return a collection field directly, such as => _items, typed as IReadOnlyList<T>, IEnumerable<T> or IReadOnlyDictionary<TKey, TValue>. Each one hands callers your live state.
  2. Choose a view or a snapshotIf callers only read the data right away and should see later updates, return AsReadOnly(). If they keep it, cache it or read it from another thread, give them an immutable snapshot.
  3. Replace, don't mutateFor data that changes now and then, like rates, settings or permissions, build a new immutable collection and swap the reference. Lookup tables built once at startup are a good fit for ToFrozenSet() and ToFrozenDictionary().
  4. Make the elements immutable tooAn immutable list of mutable objects is still mutable data. Use records with init-only properties, or readonly record struct, for the items you share.

Key takeaways

  • readonly on a reference-type field freezes which object the field points to, not the object's contents.
  • IReadOnlyList<T> is a view: the owner can still change the list, a cast can unlock it, and elements may be mutable.
  • ReadOnlyCollection<T> blocks the cast but still shows every change made to the list it wraps.
  • Immutable and frozen collections protect the data itself; swap in a new snapshot instead of editing the old one.
  • Put the real guarantee in your API's return type so callers know what they can rely on.

📚 المصادر

  1. readonly keyword (C# reference) — Microsoft Learn
  2. IReadOnlyList<T> Interface — Microsoft Learn
  3. ReadOnlyCollection<T> Class — Microsoft Learn
  4. System.Collections.Immutable Namespace — Microsoft Learn
  5. System.Collections.Frozen Namespace — Microsoft Learn

التعليقات (0)