A C# report keeps the ReadOnlyCollection<Student> that Course.Students returned, and its Count later changes; why, and when should Course return a copy?
answer
- wrapper, not snapshot
- Count => list.Count
- the owner keeps writing
- cheap property, costly method
- ToArray for a frozen picture
basics
~20 sReadOnlyCollection<T> is a live view: it holds a reference to the owner's list and forwards every read, so later enrolments show through it. Return a copy, such as ToArray(), when a caller needs a stable snapshot.
solid answer
~50 s`new ReadOnlyCollection<T>(list)` and `List<T>.AsReadOnly()` store a reference to the list and copy nothing; `Count` is `list.Count` and the indexer reads `list[index]`. The report therefore sees every student `Course` enrols after it took the reference, and a `foreach` over the view while `Course` adds a student throws `InvalidOperationException` from the list's enumerator. That is the intended contract: the view stops the caller writing, not the owner. When the caller needs a picture that will not move (a printed roster, data handed to another thread, a value compared later), return a copy from a method: `_students.ToArray()` typed as `IReadOnlyList<Student>` costs O(n) once and is then independent of the course. The .NET design guidelines say properties should return live collections and not snapshots, so a cheap `Students` property returns the view and a `GetRosterSnapshot()` method returns the copy.
code
csharp · 28 linesusing System.Collections.ObjectModel;
var course = new Course();
course.Enrol("Ana");
course.Enrol("Ben");
IReadOnlyList<string> view = course.Students; // live view
IReadOnlyList<string> snapshot = course.GetRosterSnapshot(); // copy
course.Enrol("Cy");
Console.WriteLine($"view: {view.Count}, snapshot: {snapshot.Count}");
try
{
foreach (var name in view)
if (name == "Ana") course.Enrol("Dee");
}
catch (InvalidOperationException e) { Console.WriteLine(e.GetType().Name); }
class Course
{
private readonly List<string> _students = new();
private readonly ReadOnlyCollection<string> _view;
public Course() => _view = _students.AsReadOnly();
public IReadOnlyList<string> Students => _view;
public IReadOnlyList<string> GetRosterSnapshot() => _students.ToArray();
public void Enrol(string name) => _students.Add(name);
}go deeper
Know that ReadOnlyCollection<T> wraps the list rather than copying it, so the owner's later changes show through.
Trace the delegation (Count and the indexer read the wrapped list) and explain why enumerating the view during an owner's Add throws InvalidOperationException.
Pick live view versus snapshot per caller, place each behind a property or a named method, and say what a view does not give you on other threads.
Decide when per-call snapshots become costly enough that the owning type should switch to immutable or frozen storage, and how that changes the class's contract.
## What the wrapper actually holds `ReadOnlyCollection<T>` (namespace `System.Collections.ObjectModel`) has one constructor, `ReadOnlyCollection(IList<T> list)`, and it stores that reference in a private field. Nothing is copied. Its members delegate: - `Count` returns `list.Count`. - The indexer returns `list[index]`. - `Contains`, `IndexOf`, `CopyTo` and `GetEnumerator` call the same members on the list. `List<T>.AsReadOnly()` is `new ReadOnlyCollection<T>(this)`, and the `AsReadOnly()` extension on `IList<T>` does the same. So the object a caller receives is a **view**: a window onto the owner's list that blocks writes through the window but shows whatever is behind it right now. ## What the report sees Suppose a reporting job reads `course.Students` at nine o'clock, keeps the reference, and formats it at five past. Between those times `Course.Enrol` adds two students. Three consequences follow: 1. **`Count` changes.** The report prints the five-past roster, not the nine o'clock one. 2. **Enumeration can fail.** If `Course` adds a student while the report is inside a `foreach` over the view, the next step of the loop throws `InvalidOperationException`, because the view hands out the list's own enumerator and that enumerator checks the list's version. The details of that check belong to the material on the enumerator contract. 3. **Threads are not protected.** A view is not a lock. Reading it on one thread while the owner writes on another is the same unsynchronised access to a `List<T>` as reading the list directly. None of this is a bug in the wrapper. A read-only view promises that **the holder of the view** cannot change the list; it never promised that **nobody** can. ## Live view or snapshot The .NET design guidelines name the two shapes: a **live collection** always represents the current state, a **snapshot collection** represents the state at one moment. They also give the placement rule: "DO NOT return snapshot collections from properties. Properties should return live collections", because a property getter should be cheap and a snapshot costs an O(n) copy. | Need of the caller | Return | Cost | Later changes visible? | |---|---|---|---| | Read the current roster, often | cached `ReadOnlyCollection<Student>` from a property | O(1), no allocation per read | yes | | Keep a picture that will not move | a copy from a method | O(n) once per call | no | | Share across threads without locks | an immutable collection | depends on the type | no; covered with immutable collections | ## Making the copy Several expressions produce an independent copy that can be returned as `IReadOnlyList<Student>`: - **`_students.ToArray()`**: the smallest copy. A caller could cast the result back to `Student[]` and change elements, but only of its own copy; the course is unaffected. - **`_students.ToList()`**: the same independence with a growable list, usually more than a caller needs. - **`[.. _students]` assigned to an `IReadOnlyList<Student>`**: a C# 12 collection expression. For a read-only interface target the compiler builds a copy in a type of its own choosing, not a `List<T>`; on the current compiler it reports `IsReadOnly` as `true`. - **`new ReadOnlyCollection<Student>(_students.ToArray())`**: a copy behind a wrapper, when the copy should also refuse writes through `IList<T>`. Name the method for what it does, for example `GetRosterSnapshot()`, so readers do not expect a live view, and avoid calling it in a loop where one copy outside the loop would do. ## Choosing in practice The decision is per caller, not per class: one `Course` can offer both shapes, and most domain classes should, because their callers differ. - A UI list bound to the roster, or a validator that runs right away, wants the **live view**: cheap and always current. - A report, an export, an audit record or a message queued for later wants a **snapshot**, taken under whatever synchronisation the owner already uses. - If many readers on many threads need snapshots all the time, copying on every call gets expensive, and switching the owner to an immutable or frozen collection becomes the better design. - If a caller keeps the view and is surprised by its changes, the fix belongs in the API's naming and documentation as much as in the code: a property called `Students` that returns a live view is the guideline-conforming design, and a caller who needs a stable copy should call the snapshot method.
- Is a ReadOnlyCollection<Student> view safe to read on another thread while Course keeps enrolling?No. Every read is forwarded to the underlying `List<Student>`, and `List<T>` is not safe for a reader and a writer at the same time. The wrapper adds no synchronisation. Either take a snapshot under the owner's lock and hand that out, or move the owner to a collection designed for concurrent or immutable access.
- Why do the .NET design guidelines say a property should not return a snapshot?Callers treat a property read as cheap and may read it repeatedly, for example in a loop condition. A snapshot property copies the whole collection on every read, an O(n) allocation each time. Live collections from properties and snapshots from methods with an explicit name keep the cost visible at the call site.
- Does wrapping a copy, new ReadOnlyCollection<Student>(_students.ToArray()), add anything over returning the array?It stops the receiver from writing elements through a cast: an array returned as `IReadOnlyList<Student>` can be cast back to `Student[]` and its elements replaced, while the wrapper's indexer setter throws `NotSupportedException`. Either way the course itself is safe, because both are copies; the wrapper only protects the copy for whoever receives it next.
A ReadOnlyCollection<T> is a shop window onto the stockroom: passers-by cannot touch the shelves, but they see every change the shopkeeper makes behind the glass. A snapshot is a photograph of that window: it never changes, and it starts going out of date the moment it is taken.
- AsReadOnly() copies the list, so later changes do not appear.
- A read-only view is thread-safe because nobody can write to it.
- A property getter should return a fresh copy on every read.
- Handing out a view stops the owner from changing its own list.
- ToArray() returned as IReadOnlyList<T> still changes with the owner.