
What readonly and IReadOnlyList Really Protect, and What They Leave Open
- كاتب موثّق
- .NET 10
محتويات المقال
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
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.
What actually happens
readonly freezes the variable, not the object
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.
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); // 0Rate had a settable Value, cache.Rates[0].Value = 0 would compile without any cast.
ReadOnlyCollection blocks the cast, not the changes
_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
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
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 }}using System.Collections.Immutable;public sealed class RateCache{ private ImmutableArray<Rate> _rates = []; // A snapshot: nobody can change it, not even this class public ImmutableArray<Rate> Rates => _rates; public void Refresh(IEnumerable<Rate> fresh) { _rates = [.. fresh]; // build a new snapshot, then publish it }}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
readonly field | ||
IReadOnlyList<T> | ||
ReadOnlyCollection<T> | List<T> | |
ImmutableArray<T>, ImmutableList<T> | ||
FrozenSet<T>, FrozenDictionary<TKey, TValue> |
How to apply it in your project
Find the leaky properties Search for properties that return a collection field directly, such as => _items, typed asIReadOnlyList<T>,IEnumerable<T>orIReadOnlyDictionary<TKey, TValue>. Each one hands callers your live state.Choose a view or a snapshot If 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.Replace, don't mutate For 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()andToFrozenDictionary().Make the elements immutable too An 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
readonlyon 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.
التعليقات (0)