skip to content

A C# Course class returns its private List<Student> as IReadOnlyList<Student>; how can a caller still add students, and how do you stop it?

level: middleimportance: must knowfreq 60%

answer

  1. the static type, not the object
  2. an explicit cast compiles
  3. is List<Student> succeeds
  4. a wrapper with no list to recover
  5. AsReadOnly, cached in a field

basics

~10 s

Returning the list through IReadOnlyList<Student> narrows only the reference; the object is still the List<Student>, so a caller can cast it back and call Add. Return a ReadOnlyCollection<Student> wrapper from AsReadOnly() instead.

solid answer

~40 s

An interface return type changes what the compiler lets the caller write, not what the object is. `course.Students is List<Student> raw` succeeds at run time, and `raw.Add(...)` changes the course's private roster; an explicit cast from an interface to a class always compiles. The fix is to return an object that holds the list but is not the list: `_students.AsReadOnly()` returns a `ReadOnlyCollection<Student>` that implements `IReadOnlyList<Student>` and `IList<Student>`, forwards reads, and throws `NotSupportedException` ("Collection is read-only.") from `Add`, `Insert`, `Remove`, `Clear` and the indexer setter reached through `IList<Student>`. A cast to `List<Student>` now fails with `InvalidCastException`. Create the wrapper once, in the constructor, and keep it in a field, because each `AsReadOnly()` call allocates a new one. For a private `Dictionary<TKey,TValue>`, the `AsReadOnly()` extension returns a `ReadOnlyDictionary<TKey,TValue>` the same way.

code

csharp · 25 lines
csharp
using System.Collections.ObjectModel;

var course = new Course();
course.Enrol(new Student("Ana"));

if (course.StudentsLeaky is List<Student> raw)
    raw.Add(new Student("Mallory"));            // succeeds: it is the real list
Console.WriteLine(course.StudentsLeaky.Count);  // 2

IReadOnlyList<Student> safe = course.Students;
Console.WriteLine(safe is List<Student>);       // False
try { ((IList<Student>)safe).Add(new Student("Eve")); }
catch (NotSupportedException e) { Console.WriteLine(e.Message); }

public record Student(string Name);

public class Course
{
    private readonly List<Student> _students = new();
    private readonly ReadOnlyCollection<Student> _view;
    public Course() => _view = _students.AsReadOnly();
    public void Enrol(Student s) => _students.Add(s);
    public IReadOnlyList<Student> StudentsLeaky => _students;
    public IReadOnlyList<Student> Students => _view;
}

go deeper

for a junior

Remember that an interface return type does not change the object: a List<T> returned as IReadOnlyList<T> is still a List<T>.

for a middle

Explain the reference conversion, why the explicit cast compiles and succeeds, and how a ReadOnlyCollection<T> wrapper with explicit mutators closes the hole.

for a senior

Show the production wiring: a cached wrapper, mutations only through domain methods, the dictionary equivalent, and the wrapper's limits (shallow, a live view, not a security boundary).

for a principal

Weigh a wrapper against copies or immutable types as a team convention for domain classes: allocation per read, loud failure on misuse and how much each costs to enforce in review.

## The leak A domain class that owns a list usually wants other code to read it and only its own methods to change it. A common first attempt is to keep a `List<Student>` in a private field and expose it through a read-only interface: ```csharp public IReadOnlyList<Student> Students => _students; ``` That line compiles because `List<T>` implements `IReadOnlyList<T>`, and it does stop **casual** mutation: through an `IReadOnlyList<Student>` reference the compiler finds no `Add`. But the conversion is a **reference conversion**: the object handed out is the same `List<Student>` instance, only seen through a narrower type. Any caller can recover it: - `course.Students is List<Student> raw` is a type test at run time, and it succeeds. - `((List<Student>)course.Students).Add(...)` compiles, because C# permits an explicit conversion from an interface to a non-sealed class, and it succeeds at run time for the same reason. - Code that tries `course.Students as IList<Student>` gets a non-null result and can call `Add`, `Insert` and `Clear`. In a library that other teams reference, "nobody would do that" is not a design. Sooner or later a reporting screen sorts the list in place, or a controller appends a test student, and the class invariants (capacity limits, enrolment events) are bypassed. ## The fix: hand out a wrapper `List<T>.AsReadOnly()` returns a `ReadOnlyCollection<T>`; in the runtime source it is simply `new ReadOnlyCollection<T>(this)`. The wrapper stores a reference to the list in a private field and: | Operation on the wrapper | Result | |---|---| | `Count`, the indexer `get`, `Contains`, `IndexOf`, `foreach` | forwarded to the list | | `Add`, `Insert`, `Remove`, `RemoveAt`, `Clear` through `IList<T>` or `ICollection<T>` | `NotSupportedException`: "Collection is read-only." | | the indexer `set` through `IList<T>` | `NotSupportedException` | | `ICollection<T>.IsReadOnly` | `true` | | a cast to `List<T>` | `InvalidCastException`; the wrapper is not a list | The mutating members are implemented **explicitly**, so they do not appear on a `ReadOnlyCollection<T>` variable at all; they exist only so the type can be passed to APIs that take `IList<T>`. ## Wiring it into the class 1. Keep the `List<Student>` private and `readonly`, so the field is never replaced. 2. Create the wrapper once, in the constructor or a field initializer, and keep it in a second field. Each `AsReadOnly()` call allocates a new wrapper (two calls return different objects), so calling it in a getter allocates on every read. 3. Expose the wrapper as `IReadOnlyList<Student>` or as `ReadOnlyCollection<Student>`; which of the two a published API should choose is a separate versioning decision. 4. Route every change through methods such as `Enrol` and `Withdraw`, where the invariants live. The same leak and the same fix apply to dictionaries. A `Dictionary<string, Student>` returned as `IReadOnlyDictionary<string, Student>` can be cast back; the `AsReadOnly()` extension method on `IDictionary<TKey,TValue>` returns a `ReadOnlyDictionary<TKey,TValue>` wrapper whose mutators throw `NotSupportedException`. ## What the wrapper does not do - **It is a view, not a copy.** The wrapper reads the owner's list on every call, so the owner's later changes show through it; when a caller needs a frozen picture, return a copy instead. - **It is shallow.** The `Student` objects inside are the same instances. If `Student` has settable properties, a caller can still change a student's name; immutable element types solve that, not the wrapper. - **It is not a security boundary.** Reflection can read the wrapper's private field. The wrapper protects the class's invariants from ordinary code, which is the job here. ## Spotting it in review - A property or method whose declared type is a read-only interface but whose body returns a private `List<T>` or `Dictionary<TKey,TValue>` field directly. - Call sites that test or cast a returned collection back to `List<T>`; they usually exist because someone needed `Add` or `Sort` and found a way. - Getters that call `AsReadOnly()` or `ToList()` on every read, which allocates each time and, for `ToList()`, hides misuse instead of reporting it. ## Why not just copy every time? Returning `_students.ToList()` from the property would also stop the leak, but it costs an O(n) copy on every read, and callers who mutate their copy get no error, only a silent no-op on the real roster. The wrapper is O(1) to hand out, fails loudly when misused, and keeps the property cheap.

  • Why keep the ReadOnlyCollection<Student> in a field instead of calling AsReadOnly() in the getter?
    `List<T>.AsReadOnly()` is `new ReadOnlyCollection<T>(this)`, so every call allocates a fresh wrapper and two calls return different objects. A getter read in a loop or on every request then adds garbage for no benefit. Creating the wrapper once and returning the cached instance gives the same protection with no allocation per read.
  • How would you expose a private Dictionary<string, Student> keyed by student ID the same way?
    Returning it as `IReadOnlyDictionary<string, Student>` has the same cast-back leak. Call the `AsReadOnly()` extension on `IDictionary<TKey,TValue>`, cache the resulting `ReadOnlyDictionary<string, Student>`, and expose that; its `Add`, `Remove` and indexer setter throw `NotSupportedException`, and it still reflects the owner's later changes.
  • Does the wrapper stop a caller from renaming a Student in the list?
    No. `ReadOnlyCollection<T>` blocks changes to which items are in the list, not changes inside an item. If `Student` exposes a settable `Name`, `course.Students[0].Name = "x"` still works. Make the element type immutable, or expose read-only projections of it.

  • Returning IReadOnlyList<T> makes the private list impossible to modify.
  • A cast from IReadOnlyList<T> back to List<T> does not compile.
  • Marking the List<T> field readonly stops callers from adding items.
  • AsReadOnly() takes a copy, so it is fine to call in every getter.
  • The read-only wrapper also makes each Student object immutable.