skip to content

In C#, why does a class that keeps a List<T>.Enumerator in a readonly field return the default value forever instead of advancing?

level: seniorimportance: nice to knowfreq 20%

answer

  1. mutable struct, read-only storage
  2. defensive copy on member call
  3. the field's index never moves
  4. MoveNext true, Current default

basics

~10 s

List<T>.Enumerator is a mutable struct, and calling MoveNext on a readonly struct field runs on a defensive copy. The field never advances, so MoveNext keeps returning true and Current keeps returning default(T).

solid answer

~40 s

`List<T>.Enumerator` keeps its position and current element in its own fields, and `MoveNext()` mutates them. For a `readonly` field of a struct type not declared `readonly struct`, the compiler calls each member on a hidden copy so the field cannot change. So `_e.MoveNext()` advances a temporary, the field stays at the start and reports another element on every call, and `_e.Current` reads the field's never-set value, `default(T)`. Nothing throws and nothing warns. The same split happens with `var copy = e`, passing the enumerator by value, or returning it from a property. Fix it by dropping `readonly`, holding an `IEnumerator<T>` (one box, reference semantics), or storing the list and an index; and remember a stored enumerator still throws once the list is modified.

code

csharp · 19 lines
csharp
var samples = new List<int> { 10, 20, 30 };

var cursor = new SampleCursor(samples);
for (int i = 0; i < 4; i++)
    Console.Write($"{cursor.Next()} ");     // 0 0 0 0
Console.WriteLine();

var e = samples.GetEnumerator();
var copy = e;                 // copies the whole enumerator state
e.MoveNext();
Console.WriteLine($"{e.Current} {copy.Current}");   // 10 0

sealed class SampleCursor(List<int> source)
{
    // readonly field of a mutable struct: each call below runs on a hidden copy
    private readonly List<int>.Enumerator _e = source.GetEnumerator();

    public int Next() => _e.MoveNext() ? _e.Current : -1;
}

go deeper

for a junior

Remember that a struct is copied on assignment, and List<T>.Enumerator is a struct whose MoveNext changes it; a copy does not move with the original.

for a middle

Explain the defensive copy: a member call on a readonly field of a non-readonly struct runs on a temporary, so MoveNext advances the temporary and the field stays put.

for a senior

Diagnose the symptom from its output, MoveNext always true and Current always default, and choose a fix: a mutable field, a boxed IEnumerator<T>, or an index, with the version check in mind.

for a principal

Set a review rule for enumerators held outside foreach: name an owner, decide who disposes, and prefer an index or IEnumerator<T> unless a measured allocation justifies a mutable struct field.

## The symptom A class keeps a `List<T>.Enumerator` in a field so it can hand out one element per call. The field is `readonly`, because nothing ever assigns it again. In review the class looks right, but at run time it returns `default(T)` forever, or loops forever in `while (_e.MoveNext())`. The example prints `0 0 0 0` for a list holding `10, 20, 30`. Nothing throws and the compiler reports no diagnostic. The cause is that `List<T>.Enumerator` is a **mutable struct**: its position (`_index`) and its current element (`_current`) are fields of the struct itself, and `MoveNext()` changes them. ## Why a readonly field never advances C# guarantees that a `readonly` field is not modified after construction. When code calls an instance member on a `readonly` field whose type is a struct that is not declared `readonly struct`, the compiler cannot prove the member leaves the struct unchanged, so it calls the member on a **defensive copy**. Tracing `_e.MoveNext() ? _e.Current : -1`: 1. `_e.MoveNext()` copies `_e` into a hidden temporary and advances the temporary. The field's index stays at its initial value. 2. Because the field never moved, the next `MoveNext()` on a fresh copy again sees the first element available and returns `true`. It never reaches the end. 3. `_e.Current` reads the field, whose `_current` was never set, so it returns `default(int)`, which is `0`. The result is an enumerator that always says "there is another element" and always reports the default value: a silent infinite loop in a `while`, wrong data in a pull-style API. The copy is skipped only for a `readonly struct` (or a `readonly` member), whose members the compiler knows cannot change the instance. An enumerator can never be declared that way, because `MoveNext()` exists to change it, so `List<T>.Enumerator`, `Dictionary<TKey,TValue>.Enumerator` and `HashSet<T>.Enumerator` are all ordinary mutable structs, and every one of them behaves like this in a `readonly` field. ## Other places a struct enumerator gets copied The `readonly` field is the hardest case to spot, but every copy of a mutable struct produces the same split: - **Assignment**: `var copy = e;` copies the position; advancing `e` leaves `copy` behind (the example's second line prints `10 0`). - **Passing by value**: a helper `void Skip(List<int>.Enumerator e)` advances its own copy; the caller's enumerator does not move. - **A property getter**: `List<int>.Enumerator Cursor => _e;` returns a new copy on every read, so `Cursor.MoveNext()` advances a temporary. - **An `in` parameter or a `ref readonly`** value: member calls on it work on defensive copies, as with a `readonly` field. `foreach` itself is safe: it keeps the enumerator in a hidden, mutable local and calls `MoveNext` on that variable directly. The trouble starts only when code takes the enumerator out of `foreach` and stores or passes it. ## Fixes | Fix | Effect | Cost | |---|---|---| | Remove `readonly` from the field | calls run on the field itself and it advances | needs a comment so nobody adds `readonly` back | | Store `IEnumerator<T>` instead | the struct is boxed once; the field holds a reference, so calls mutate the one boxed object | one heap allocation | | Store the `List<T>` and an `int` index | no enumerator to copy | gives up the version check | | Pass the enumerator with `ref` | the helper advances the caller's variable | callers must write `ref` | Two further points apply to any long-lived enumerator held in a field: - `List<T>.Enumerator` records the list's version when it is created, so if the list changes later, the next `MoveNext()` throws `InvalidOperationException`. A stored enumerator is a snapshot of one moment, not a cursor that survives edits. - An enumerator taken out of `foreach` is no longer disposed for you. `List<T>.Enumerator.Dispose()` does nothing, but an enumerator over a file or a pooled buffer must be disposed by whoever stores it. ## What to say in a review Ask why the code stores an enumerator at all. A field that holds an enumerator is usually a pull-style reader that would be clearer as an index into the collection, or as an `IEnumerator<T>` with an explicit owner who disposes it. If the struct is kept for allocation reasons, the field must be mutable and must never be exposed through a property, and a comment should say why `readonly` is missing.

  • In C#, why does storing the enumerator as IEnumerator<T> in a readonly field fix the problem?
    Assigning `List<T>.Enumerator` to `IEnumerator<T>` boxes it once. The field then holds a reference to that heap object, and `readonly` only stops the reference being reassigned. Calls to `MoveNext()` go through the reference and mutate the single boxed enumerator, so it advances. The price is one allocation and interface calls.
  • A class stores a List<T>.Enumerator in a mutable field and works, until another method adds to the list. What happens next?
    The enumerator captured the list's version when it was created. `Add` increments the list's version, so the stored enumerator's next `MoveNext()` throws `InvalidOperationException` ("Collection was modified; enumeration operation may not execute."). A stored enumerator cannot outlive changes to its list.

  • Marking the enumerator field readonly is harmless because the field is never reassigned.
  • The compiler reports an error when MoveNext is called on a readonly struct field.
  • A copied struct enumerator shares its position with the original.
  • foreach over a List<T> suffers the same copy problem as the field.
  • MoveNext on the readonly field returns false at once, so the loop never runs.