What does the C# compiler generate for an iterator method returning IEnumerable<T>, and what jobs do its state and hoisted fields do?
answer
- a nested sealed class
- one object, five interfaces
- locals become fields
- a switch on the state
- Reset is not supported
basics
~20 sA private nested sealed class implementing IEnumerable<T>, IEnumerator<T> and IDisposable. Parameters and locals that live across a yield become fields, a state field records where the body paused, and MoveNext jumps back there; the method itself just creates the object.
solid answer
~50 sThe compiler moves the body into a private nested sealed class (Roslyn names it like `<Countdown>d__0`) that implements `IEnumerable<T>`, `IEnumerable`, `IEnumerator<T>`, `IEnumerator` and `IDisposable`, and the method shrinks to creating that object and storing the arguments. `MoveNext()` holds the body rewritten as a switch on a **state** field: it jumps to the last resume point, runs to the next `yield return`, stores the value in a current field, records the new state and returns `true`. Locals that live across a `yield return` are **hoisted** into fields because the stack frame is gone between calls; each parameter gets a working copy plus a saved original, so every enumerator restarts with the real arguments. `GetEnumerator()` returns the object itself on the first call from the creating thread and a new instance otherwise; `Dispose()` runs pending `finally` blocks; `Reset()` throws `NotSupportedException`.
code
csharp · 26 lines#:property PublishAot=false
using System.Reflection;
IEnumerable<int> seq = Timers.Countdown(3);
Type t = seq.GetType();
Console.WriteLine(t.FullName);
Console.WriteLine(string.Join(", ", t.GetInterfaces().Select(i => i.Name)));
foreach (FieldInfo f in t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
Console.WriteLine($" {f.FieldType.Name} {f.Name}");
IEnumerator<int> first = seq.GetEnumerator();
IEnumerator<int> second = seq.GetEnumerator();
Console.WriteLine($"first is seq: {ReferenceEquals(first, seq)}, second is seq: {ReferenceEquals(second, seq)}");
first.MoveNext();
try { first.Reset(); }
catch (NotSupportedException) { Console.WriteLine("Reset threw NotSupportedException"); }
static class Timers
{
public static IEnumerable<int> Countdown(int from)
{
for (int i = from; i > 0; i--)
yield return i;
}
}go deeper
Recall that the compiler turns an iterator into a hidden class whose MoveNext runs your code a piece at a time, and that the class is also the enumerator.
Explain the state field, the current field, hoisted locals and the saved copy of each parameter, and why Reset throws NotSupportedException.
Use the model in diagnosis: read MoveNext frames in stack traces, account for the state machine allocation in hot paths, and know when GetEnumerator reuses the object.
Judge when the convenience of yield is worth its cost against a hand-written struct enumerator, for example in a tight game or telemetry loop that must not allocate.
## The method becomes a constructor call For an iterator method, the C# compiler does not emit your body as the method's code. It generates a **private nested sealed class**, named something like `<Countdown>d__0`, and rewrites the method itself to do only three things: create an instance of that class, copy the arguments into its fields, and return it. The method also gets an `[IteratorStateMachine(typeof(...))]` attribute pointing at the generated type, which tools such as debuggers and decompilers can use to find it. The names are implementation details of the Roslyn compiler, not part of the language, but they are stable enough to recognise in stack traces and decompilers. The snippet in this question prints them using reflection. ## One object, five interfaces The generated class implements: - `IEnumerable<T>` and `IEnumerable`, so the method's result can be used in `foreach`; - `IEnumerator<T>` and `IEnumerator`, so the same object can also act as the enumerator; - `IDisposable`, so `foreach` can stop it early and run pending `finally` blocks. For an iterator declared to return `IEnumerator<T>`, the class implements only the enumerator interfaces and `IDisposable`. ## The fields | Field (Roslyn naming) | Job | |---|---| | `<>1__state` | where the body is paused, or whether it is running, finished or not yet enumerated | | `<>2__current` | the last value produced, returned by `Current` | | `<>l__initialThreadId` | the managed thread that created the object | | `from` | the working copy of the parameter the body reads and may change | | `<>3__from` | the original argument, copied into `from` for each new enumerator | | `<i>5__1` | a **hoisted local**: a local variable moved into a field so it survives across a `yield return` | Locals that live across a `yield return` must become fields, because the method's stack frame is gone between `MoveNext()` calls. A Debug build hoists more locals than strictly necessary so the debugger can show them. ## MoveNext is your body, cut at each yield `MoveNext()` contains your original code, rewritten as a **switch on the state field**: 1. On entry it jumps to the point that matches the current state: the start of the body, or just after a particular `yield return`. 2. It runs your code until the next `yield return expr`. 3. There it stores `expr` in the current-value field, records a state number for that resume point, and returns `true`. 4. When the body reaches its end or a `yield break`, it marks the state as finished and returns `false`. A simplified sketch for a countdown loop (not literal compiler output): ```csharp bool MoveNext() { switch (state) { case 0: state = -1; i = from; break; // first call: start of body case 1: state = -1; i--; break; // resume after the yield default: return false; } if (i > 0) { current = i; state = 1; return true; } return false; } ``` ## GetEnumerator, Reset and Dispose - **GetEnumerator()** checks whether this object has not been enumerated yet and whether the call comes from the thread that created it. If both hold, it returns **the object itself**, saving an allocation for the common `var seq = M(); foreach (...)` case. Otherwise it creates a fresh instance. Either way it copies the original arguments in, so each enumeration starts from the top. - **Reset()** throws `NotSupportedException`. A compiler-generated iterator cannot rewind; to restart, call `GetEnumerator()` again or call the iterator method again. - **Dispose()** runs the `finally` blocks around the paused `yield return` and marks the iterator finished. ## Why it matters in practice - The only allocation for a plain iterator call is the state machine object itself, plus whatever the body allocates. - Mutating a parameter inside the body is safe across enumerations, because each enumerator starts from the saved original argument. - Seeing `<Countdown>d__0.MoveNext()` in a stack trace tells you the exception came from inside an iterator body during enumeration, not from the call that created it. - Because the method only builds the object, anything at the top of the body, including argument checks, runs on the first `MoveNext()`, not at the call. - The same rewriting idea, a method cut into resumable pieces with its locals stored in fields, underlies async methods, which is why the two features share restrictions on what may live across a suspension point.
- Why does the C# iterator's GetEnumerator() return the object itself only on the creating thread?Reusing the enumerable as its own enumerator saves an allocation in the common case of calling the method and looping at once. Handing that one object to two threads, or to two enumerations, would make them share state, so the generated code reuses it only if it has not been enumerated yet and the caller is on the thread that created it; otherwise it allocates a fresh instance.
- Why does a compiler-generated C# iterator throw NotSupportedException from Reset()?Rewinding would mean undoing whatever the body has already done, which the compiler cannot do in general, so the generated `Reset()` simply throws `NotSupportedException`. `foreach` never calls `Reset()`; to start again, call `GetEnumerator()` again or call the iterator method again, and the body reruns from the top.
- What tells you, in a stack trace, that an exception came from inside a C# iterator body?A frame such as `<Countdown>d__0.MoveNext()`: the generated class name wraps the method name, and the frame is `MoveNext` rather than the method itself. It means the exception happened during enumeration, so look at the consumer's loop for the call site, not at the line that called the iterator.
- The compiler turns an iterator into a hidden List<T> filled at the call
- Iterator locals live on the stack between MoveNext calls
- Each yield return starts a new thread or task
- Reset() rewinds a compiler-generated iterator to its first element
- GetEnumerator() always allocates a new enumerator object