DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

How a yield return iterator decompiles

Write a three-line method that returns IEnumerable<int> and uses yield return, compile it, and open the assembly. Your method is gone. In its place sits a compiler-generated class with a name like <Window>d__0, half a dozen fields whose names begin with <>, and a MoveNext() that is one flat switch over an integer. The loop you wrote has been turned inside out. Rebuilding your yield return from that switch is a decompiler's job, and it is a good example of how much machinery one keyword hides.

The real question

yield return makes a method resumable. It returns a value, freezes every local, and continues from the next statement when the consumer pulls again. A normal method cannot do that — its stack frame is gone the moment it returns. So the compiler has to move the method's state somewhere that outlives a return, and it has to turn straight-line code with a loop into something that can be re-entered at any suspension point.

The answer is a generated class that is its own enumerable, enumerator and disposable, with a single <>1__state field that says where execution is parked. Read that class's shape and read the switch at the top of MoveNext, and the original method falls out.

The method becomes a stub

Here is the source. One yield return inside a try/finally, so the interesting cleanup plumbing shows up:

public static IEnumerable<int> Window(int[] source)
{
    Console.WriteLine("start");
    try
    {
        for (int i = 0; i < source.Length; i++)
        {
            yield return source[i];
        }
    }
    finally
    {
        Console.WriteLine("done");
    }
}
Enter fullscreen mode Exit fullscreen mode

After compilation, Window no longer contains any of that. It is a two-line stub that constructs the state machine and returns it — and it is stamped with an attribute that names the generated type:

[IteratorStateMachine(typeof(<Window>d__0))]
public static IEnumerable<int> Window(int[] source)
{
    <Window>d__0 d = new <Window>d__0(-2);
    d.<>3__source = source;
    return d;
}
Enter fullscreen mode Exit fullscreen mode

The -2 passed to the constructor is the initial state, and <>3__source is where the argument is parked until an enumerator is created. The [IteratorStateMachine] attribute is the first thing Glass keys on: it is the compiler telling you exactly which nested type holds the real body.

The generated class

[CompilerGenerated]
private sealed class <Window>d__0 :
    IEnumerable<int>, IEnumerable,
    IEnumerator<int>, IEnumerator,
    IDisposable
{
    private int <>1__state;
    private int <>2__current;
    private int <>l__initialThreadId;

    private int[] source;
    public int[] <>3__source;

    private int <i>5__2;

    public <Window>d__0(int <>1__state)
    {
        this.<>1__state = <>1__state;
        this.<>l__initialThreadId = Environment.CurrentManagedThreadId;
    }

    int IEnumerator<int>.Current => <>2__current;
    object IEnumerator.Current => <>2__current;
    // MoveNext, GetEnumerator, Dispose, Reset, <>m__Finally1 ...
}
Enter fullscreen mode Exit fullscreen mode

Every field earns its place. <>1__state is the resume label. <>2__current holds the value the last yield return produced, and is what Current returns. <>l__initialThreadId is a thread-identity stamp used by the enumerable-reuse trick below. <i>5__2 is the loop variable i, hoisted out of the stack and into a field because its value has to survive each suspension. And the pair source / <>3__source is the parameter: <>3__source is the copy the enumerable keeps, and source is the copy the active enumerator reads.

Note this is a class, not a struct. A synchronous iterator is always a reference type, because the enumerable has to be handed around and enumerated by reference. (The async iterator is the opposite — a mutable struct — which is one of several reasons the two are different machines and Glass fingerprints them separately.)

The thread-id reuse trick

A method returning IEnumerable<T> has a subtle obligation: every call to GetEnumerator() must yield a fresh, independent cursor. The naive implementation allocates the state machine twice — once as the enumerable Window returns, and again each time someone calls GetEnumerator. The compiler avoids the common-case second allocation with <>l__initialThreadId:

IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
    <Window>d__0 result;
    if (<>1__state == -2 &&
        <>l__initialThreadId == Environment.CurrentManagedThreadId)
    {
        <>1__state = 0;
        result = this;
    }
    else
    {
        result = new <Window>d__0(0);
    }
    result.source = <>3__source;
    return result;
}
Enter fullscreen mode Exit fullscreen mode

In IL the guard is two compares and a branch:

ldarg.0
ldfld      int32 '<Window>d__0'::'<>1__state'
ldc.i4.s   -2
bne.un.s   IL_alloc
ldarg.0
ldfld      int32 '<Window>d__0'::'<>l__initialThreadId'
call       int32 [System.Private.CoreLib]System.Environment::get_CurrentManagedThreadId()
bne.un.s   IL_alloc
ldarg.0
ldc.i4.0
stfld      int32 '<Window>d__0'::'<>1__state'
ldarg.0
stloc.0
br.s       IL_copy
IL_alloc:
ldc.i4.0
newobj     instance void '<Window>d__0'::.ctor(int32)
stloc.0
IL_copy:
// result.source = <>3__source; return result;
Enter fullscreen mode Exit fullscreen mode

The very first foreach — on the same thread that called Window, with the object still in its pristine -2 state — reuses this and allocates nothing. A second enumeration, or one from another thread, falls to newobj. This is pure foreach plumbing; it has no counterpart in the source, so Glass drops it entirely.

<>1__state drives MoveNext

The heart of the machine is MoveNext. It is a switch on <>1__state that routes to the right resume point, runs until the next yield return or the end, and leaves the state field pointing at where to come back to:

private bool MoveNext()
{
    switch (<>1__state)
    {
    default:
        return false;
    case 0:
        <>1__state = -1;
        Console.WriteLine("start");
        <>1__state = -3;          // now inside the try that has a finally
        <i>5__2 = 0;
        break;
    case 1:
        <>1__state = -3;
        <i>5__2++;
        break;
    }
    if (<i>5__2 < source.Length)
    {
        <>2__current = source[<i>5__2];
        <>1__state = 1;           // park here; next call resumes at case 1
        return true;
    }
    <>1__state = -1;
    <>m__Finally1();              // loop finished: run the finally inline
    return false;
}
Enter fullscreen mode Exit fullscreen mode

Follow the states. 0 is first entry: run the pre-loop code, then step into the protected region (state -3) and initialise i. The yield return itself is three instructions — stash the value in <>2__current, set <>1__state = 1, return true:

ldarg.0
ldarg.0
ldfld      int32[] '<Window>d__0'::source
ldarg.0
ldfld      int32 '<Window>d__0'::'<i>5__2'
ldelem.i4
stfld      int32 '<Window>d__0'::'<>2__current'
ldarg.0
ldc.i4.1
stfld      int32 '<Window>d__0'::'<>1__state'
ldc.i4.1
ret
Enter fullscreen mode Exit fullscreen mode

When MoveNext is called again, the switch lands on case 1, increments i, and re-tests the loop condition. When i runs off the end, the method sets state to -1, calls the finally, and returns false. That -3 "running inside a try/finally" state is the signal that there is cleanup to do if the iterator is abandoned.

The <Window>d_0 lifecycle. <>1_state is the program counter: −2 idle, 0 entry, 1 parked at the yield return, −3 running inside the try, −1 finished. Dispose runs the extracted finally if the iterator is abandoned mid-stream.

The finally that cannot be a finally

The try/finally the author wrote cannot survive as a real IL finally, because MoveNext returns in the middle of the try on every yield. So the compiler lifts the finally body into its own method and calls it from the two places cleanup can happen — the normal end of the loop, and early abandonment:

private void <>m__Finally1()
{
    <>1__state = -1;
    Console.WriteLine("done");
}

void IDisposable.Dispose()
{
    int state = <>1__state;
    if (state == 1 || state == -3)
    {
        try { }
        finally { <>m__Finally1(); }
    }
}
Enter fullscreen mode Exit fullscreen mode

This is why a foreach compiles the enumerator in a using: when you break out of a foreach early, the generated Dispose() fires, sees the iterator parked inside the protected region, and runs your finally exactly once. That guarantee — finally runs even if the consumer walks away mid-stream — is the whole reason the extracted-method dance exists.

How Glass maps it back

Glass does not execute the machine; it reads it. The reconstruction is a fixed sequence:

  1. Fingerprint the type. A [CompilerGenerated] nested class that implements IEnumerable<T> + IEnumerator<T> + IDisposable, carries <>1__state and <>2__current but no builder and no IValueTaskSource, and is named by an [IteratorStateMachine] attribute on the stub — that is a synchronous iterator, and nothing else. (The presence of a builder would mark it async; its absence is the tell.)
  2. Recover parameters and locals. The <>3__-prefixed fields map back to the method's parameters; the <name>5__N fields are hoisted locals that become ordinary int i, StreamReader reader, and so on.
  3. Read the dispatch. The switch (<>1__state) at the top of MoveNext enumerates every resume point. Glass classifies each: a case reached right after a return true that stored into <>2__current is a yield return; the -1/return false paths are yield break or the end of the method.
  4. Fold the control flow. The gotos the compiler used to jump between states are folded back into the original for; the <>m__Finally1() calls are matched to the try/finally (or using); the thread-id reuse and the <>3__-copy are discarded as plumbing. What comes out is the Window method you wrote.

From the CLI it is one command:

$ glass export ./App.dll --member "M:App.Sequences.Window(System.Int32[])"
Enter fullscreen mode Exit fullscreen mode

You get the reconstructed IEnumerable<int> Window with its yield return and try/finally intact. Add --il and Glass shows the honest other side: the <Window>d__0 class, the switch (<>1__state), the GetEnumerator thread-id check, and the extracted finally.

Caveats and where it gets hard

Two honest limits. First, the state-to-construct mapping is clean only when the yield and finally patterns match what current Roslyn emits. Hand-written IL, or a state machine from a different or older compiler, can number its states or place its cleanup differently, and then the IL view is the truthful fallback — you still see the real switch, even if the yield return cannot be named. Second, nested try/finally and yield inside multiple scopes generate several <>m__FinallyN methods and overlapping "running" states; reconstructing the exact placement of each finally, especially around an early yield break, is the subtlest part of the job, and heavy optimisation that shares hoisted locals across scopes can make the recovered loop faithful to the IL without being a character-for-character match to the original.

Takeaway

A yield return method is not really a method — it is a generated class that is enumerable, enumerator and disposable at once, with a single <>1__state integer acting as the program counter, a <>2__current holding the last value, hoisted locals promoted to fields, a thread-id trick that saves one allocation in the common foreach, and any finally extracted into a method that Dispose() can run if the consumer quits early. Glass.NET reads that fingerprint, decodes the switch (<>1__state), classifies each resume point as a yield return or yield break, and rebuilds the original loop as pure static analysis — never running a line. Grab the free build from the Glass.NET download page and open the IL view on the next iterator you need to understand, or read the decompilation docs for how the recognisers are wired.

Top comments (0)