# 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:

```csharp
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");
    }
}
```

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:

```csharp
[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;
}
```

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

```csharp
[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 ...
}
```

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`:

```csharp
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;
}
```

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;
```

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:

```csharp
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;
}
```

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
```

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.

<figure class="my-8"><svg viewBox="0 0 780 372" role="img" aria-label="Lifecycle of a synchronous yield return iterator. Construction stores state minus two. GetEnumerator on the creating thread flips state to zero and reuses the same object. MoveNext case zero runs to the first yield return, stores the value in 2__current, sets state to one, and returns true. Re-entry at case one resumes the loop and either yields again at state one or runs the finally, sets state minus one, and returns false. Dispose from a live state runs the finally once." style="width:100%;height:auto;font-family:system-ui,sans-serif"><defs><marker id="yi" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#64748b"/></marker></defs><text x="20" y="22" fill="#6366f1" font-size="13" font-weight="600">A yield return iterator, state by state</text><rect x="20" y="36" width="160" height="50" rx="7" fill="#eef2ff" stroke="#6366f1"/><text x="100" y="58" text-anchor="middle" fill="#6366f1" font-size="11" font-weight="600">new d__0(-2)</text><text x="100" y="75" text-anchor="middle" fill="#64748b" font-size="10">state = -2 (idle)</text><rect x="210" y="36" width="230" height="50" rx="7" fill="#ecfeff" stroke="#0891b2"/><text x="325" y="58" text-anchor="middle" fill="#0891b2" font-size="11" font-weight="600">GetEnumerator()</text><text x="325" y="75" text-anchor="middle" fill="#64748b" font-size="10">same thread + state -2 → reuse, state = 0</text><rect x="470" y="36" width="290" height="50" rx="7" fill="#ecfeff" stroke="#0891b2"/><text x="615" y="58" text-anchor="middle" fill="#0891b2" font-size="11" font-weight="600">MoveNext case 0</text><text x="615" y="75" text-anchor="middle" fill="#64748b" font-size="10">run pre-loop, enter try (state -3), i = 0</text><path d="M180 61 L206 61" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#yi)"/><path d="M440 61 L466 61" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#yi)"/><rect x="300" y="150" width="400" height="56" rx="7" fill="#f0fdf4" stroke="#10b981"/><text x="500" y="174" text-anchor="middle" fill="#10b981" font-size="11" font-weight="600">yield return: &lt;&gt;2__current = x; &lt;&gt;1__state = 1; return true</text><text x="500" y="192" text-anchor="middle" fill="#64748b" font-size="10">value parked in Current; consumer reads it</text><path d="M615 86 L560 146" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#yi)"/><rect x="470" y="248" width="290" height="50" rx="7" fill="#ecfeff" stroke="#0891b2"/><text x="615" y="270" text-anchor="middle" fill="#0891b2" font-size="11" font-weight="600">MoveNext case 1</text><text x="615" y="287" text-anchor="middle" fill="#64748b" font-size="10">resume: i++, re-test loop condition</text><path d="M560 206 L600 244" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#yi)"/><path d="M600 244 C640 206 660 206 640 206" fill="none" stroke="#10b981" stroke-width="1.3" stroke-dasharray="4 3" marker-end="url(#yi)"/><text x="648" y="230" fill="#10b981" font-size="10">loop → yield again</text><rect x="20" y="248" width="360" height="50" rx="7" fill="#fff7ed" stroke="#f59e0b"/><text x="200" y="270" text-anchor="middle" fill="#b45309" font-size="11" font-weight="600">loop ends: &lt;&gt;m__Finally1(); state = -1; return false</text><text x="200" y="287" text-anchor="middle" fill="#64748b" font-size="10">the finally runs inline</text><path d="M470 273 L384 273" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#yi)"/><rect x="20" y="150" width="250" height="56" rx="7" fill="#fef2f2" stroke="#ef4444"/><text x="145" y="174" text-anchor="middle" fill="#dc2626" font-size="11" font-weight="600">Dispose() from state 1 or -3</text><text x="145" y="192" text-anchor="middle" fill="#64748b" font-size="10">early break → run &lt;&gt;m__Finally1() once</text><path d="M300 178 L274 178" fill="none" stroke="#64748b" stroke-width="1.3" stroke-dasharray="4 3" marker-end="url(#yi)"/><text x="20" y="344" fill="#64748b" font-size="11">One int field — &lt;&gt;1__state — is the whole program counter: entry, each yield, done, and "inside a finally".</text></svg><figcaption class="text-sm text-muted mt-2">The <code>&lt;Window&gt;d__0</code> lifecycle. <code>&lt;&gt;1__state</code> is the program counter: −2 idle, 0 entry, 1 parked at the <code>yield return</code>, −3 running inside the try, −1 finished. <code>Dispose</code> runs the extracted finally if the iterator is abandoned mid-stream.</figcaption></figure>

## 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:

```csharp
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(); }
    }
}
```

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:

```console
$ glass export ./App.dll --member "M:App.Sequences.Window(System.Int32[])"
```

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](https://delta1labs.com/products/glass) and open the IL view on the next iterator you need to understand, or read the [decompilation docs](https://delta1labs.com/docs/glass/) for how the recognisers are wired.

