# How local functions decompile in C#


A local function looks like a lambda's quieter sibling — a little method tucked inside another method — and developers often assume they compile to the same thing. They do not, and the difference is the entire reason local functions exist: no delegate, no heap-allocated closure. The C# compiler lowers a local function to a *real method*, and when that function captures a variable it passes the captured state by `ref` in a value-type struct, so nothing is allocated on the heap just to call a helper you wrote inline.

That lowering is distinctive enough that reading it is a good way to understand what the compiler is actually doing for you. This is a working deep-dive on exactly that: the mangled method names, the `ref` display struct, the call-site IL for both the capturing and non-capturing cases, and how [Glass.NET](https://delta1labs.com/products/glass) recognizes the whole shape and folds it back into the local function you typed — instead of handing you a static method named `<Sum>g__Add|0_0` and a struct you have to reverse-engineer.

## The source

One method, two local functions. `Add` captures the enclosing `total`; `Twice` captures nothing and is marked `static` to say so.

```csharp
public static class Demo
{
    public static int Sum(int[] xs)
    {
        int total = 0;

        void Add(int v) => total += v;       // captures `total`
        static int Twice(int v) => v * 2;    // captures nothing

        foreach (var x in xs)
            Add(Twice(x));

        return total;
    }
}
```

Two local functions that read almost identically in source compile to two very different shapes, because one touches an enclosing variable and the other does not.

## What the compiler emits

`Twice` is the easy one. It captures nothing, so it becomes a plain private static method — the only unusual thing about it is the name, which the compiler mangles so you can never write it yourself:

```
.method assembly hidebysig static int32 '<Sum>g__Twice|0_1'(int32 v) cil managed
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
    ldarg.0
    ldc.i4.2
    mul
    ret
}
```

The name is `<Sum>g__Twice|0_1`: the enclosing method in angle brackets, `g__`, the original local-function name, a pipe, and an ordinal/counter pair that keeps it unique. The name between `g__` and `|` is your name, `Twice`, preserved verbatim — which is precisely what lets a decompiler recover it.

`Add` is the interesting one. It captures `total`, so the compiler hoists `total` into a *value-type* display struct and gives `Add` a `ref` parameter to it:

```
.class nested private sealed sequential ansi '<>c__DisplayClass0_0'
    extends [mscorlib]System.ValueType       // a struct, not a class
{
    .field public int32 total
}

.method assembly hidebysig static void '<Sum>g__Add|0_0'(
    int32 v,
    valuetype Demo/'<>c__DisplayClass0_0'& 'display')   // passed by ref
{
    ldarg.1              // ref display
    ldarg.1
    ldfld int32 Demo/'<>c__DisplayClass0_0'::total
    ldarg.0              // v
    add
    stfld int32 Demo/'<>c__DisplayClass0_0'::total
    ret
}
```

This is the heart of it. A lambda that captured `total` would need a *reference-type* closure object, allocated on the heap, with `total` as a field, invoked through a `Func`/`Action` delegate. The local function needs none of that: the display type is a `struct` (`extends System.ValueType`), it lives on the caller's stack, and `Add` receives it by `ref` so its writes to `total` are visible back in `Sum`. Zero allocation, no delegate.

The call site in `Sum` makes the `ref` passing explicit. The display struct is a local; calls take its address with `ldloca` and invoke the mangled methods directly with `call` — no `newobj`, no `callvirt` through a delegate:

```
.locals init (valuetype Demo/'<>c__DisplayClass0_0' display, ...)
ldloca.s   display
ldflda     int32 Demo/'<>c__DisplayClass0_0'::total   // &display.total = 0
...
// inside the loop, for Add(Twice(x)):
ldloca.s   x_current
call       int32 Demo::'<Sum>g__Twice|0_1'(int32)     // Twice(x) — plain static call
ldloca.s   display
call       void  Demo::'<Sum>g__Add|0_0'(int32, valuetype Demo/'<>c__DisplayClass0_0'&)
```

<figure class="my-8"><svg viewBox="0 0 680 240" role="img" aria-label="A capturing local function lowers to a value-type display struct holding the captured variable plus a mangled static method that takes the struct by ref, with a direct call at the call site. A naive decompiler shows the mangled method and the ref struct; Glass folds both back into a nested local function with the original name." style="width:100%;height:auto"><defs><style>.src{fill:#eef4ff;stroke:#8eb4ff}.il{fill:#fef9c3;stroke:#fde047}.st{fill:#e6fffb;stroke:#2dd4bf}.out{fill:#dcfce7;stroke:#4ade80}.t{font:600 12px system-ui;fill:#1547e0}.x{font:11px system-ui;fill:#475569}.m{font:600 10.5px ui-monospace,monospace;fill:#0f172a}.ar{stroke:#2dd4bf;stroke-width:2;fill:none}</style><marker id="l1" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#2dd4bf"/></marker></defs><rect class="src" x="12" y="30" width="150" height="80" rx="6"/><text class="t" x="24" y="52">source</text><text class="m" x="24" y="74">void Add(int v)</text><text class="m" x="24" y="90">  =&gt; total += v;</text><text class="x" x="24" y="104">captures total</text><path class="ar" d="M162 70 h40" marker-end="url(#l1)"/><rect class="il" x="206" y="12" width="220" height="92" rx="6"/><text class="t" x="218" y="32">lowered IL</text><text class="m" x="218" y="52">struct &lt;&gt;c__DisplayClass0_0</text><text class="m" x="218" y="68">  { int total; }</text><text class="m" x="218" y="86">&lt;Sum&gt;g__Add|0_0(</text><text class="m" x="218" y="100">  int v, ref display)</text><rect class="st" x="206" y="118" width="220" height="44" rx="6"/><text class="m" x="218" y="138">ldloca.s display</text><text class="m" x="218" y="154">call  &lt;Sum&gt;g__Add|0_0</text><text class="x" x="218" y="182">no newobj · no delegate · stack-allocated</text><path class="ar" d="M426 88 h40" marker-end="url(#l1)"/><rect class="out" x="470" y="30" width="196" height="80" rx="6"/><text class="t" x="482" y="52">Glass reconstruction</text><text class="m" x="482" y="76">void Add(int v)</text><text class="m" x="482" y="92">  =&gt; total += v;</text><text class="x" x="482" y="104">nested local function</text></svg></figure>

## What a naive decompiler shows

A decompiler that does not model the pattern is faithful to the metadata and therefore unreadable. It lists `<Sum>g__Twice|0_1` and `<Sum>g__Add|0_0` as sibling static methods of the class — not nested in `Sum` at all — and it surfaces the display struct as a real type with a `ref` parameter you are left to interpret:

```csharp
// Naive output: structure lost, the capture mechanism exposed.
[StructLayout(LayoutKind.Auto)]
private struct <>c__DisplayClass0_0 { public int total; }

[CompilerGenerated]
private static void <Sum>g__Add|0_0(int v, ref <>c__DisplayClass0_0 display)
    => display.total += v;

[CompilerGenerated]
private static int <Sum>g__Twice|0_1(int v) => v * 2;

public static int Sum(int[] xs)
{
    <>c__DisplayClass0_0 display = default;
    display.total = 0;
    foreach (int x in xs)
        <Sum>g__Add|0_0(<Sum>g__Twice|0_1(x), ref display);
    return display.total;
}
```

Every bit of that is correct and none of it is what you wrote. The locality is gone — `Add` and `Twice` are no longer *inside* `Sum` — and the `ref display` plumbing that the compiler added for you is now something a reader has to decode.

## What Glass reconstructs

Glass is built on [ICSharpCode.Decompiler](https://delta1labs.com/products/glass), the engine behind ILSpy, which recognizes the whole shape: the `<Enclosing>g__Name|n_m` name pattern, the `[CompilerGenerated]` marker, and the value-type display struct passed by `ref`. It reverses all three. The mangled methods are re-nested inside `Sum` as local functions named by the text between `g__` and `|`; the display struct and its `ref` threading are dissolved back into a plain captured variable; and the `static` on `Twice` is restored because its signature shows no captured state:

```csharp
// Glass output: the local functions you actually wrote.
public static int Sum(int[] xs)
{
    int total = 0;

    void Add(int v) => total += v;
    static int Twice(int v) => v * 2;

    foreach (int x in xs)
        Add(Twice(x));

    return total;
}
```

The difference from the lambda case is worth naming, because Glass shows it correctly too. Had `Add` been written as `Action<int> add = v => total += v;`, the reconstruction would show a *delegate* backed by a reference-type closure — a `newobj` of a display *class*, captured variables as its fields, and invocation through `Action`. Here there is no delegate anywhere, and Glass does not invent one: it shows a nested method and an ordinary captured local, which is the truth of the IL. Reading the two side by side in Glass is the clearest way to see, in your own code, why the guidance "prefer a local function to a lambda when you are not storing a delegate" is about allocations, not style.

## When to drop to the IL view

The reconstruction is what you want most of the time, but a few things about local functions are only visible underneath it, and Glass lets you drop straight to the IL for the same member:

- **Was the capture by `ref` or by value?** The display struct is passed by `ref` so writes propagate; confirming that in the IL (`valuetype ...DisplayClass...&`) is how you reason about whether a mutation inside the local function is seen by the caller.
- **Did the compiler elide the display struct entirely?** For a genuinely non-capturing function you will see a bare static method with only its declared parameters and no struct — the proof that marking it `static` cost nothing and allocated nothing.
- **Ordinal collisions and overloads.** The `|n_m` suffix disambiguates multiple local functions and multiple lexical scopes; the IL view is where you match a specific mangled method to a specific source position when a method has several.

Read the C# to recover intent and structure; drop to the IL when you need to prove to yourself exactly how the capture was wired. That the two views agree — a nested local function up top, a mangled static method and a `ref` struct underneath — is the whole point: Glass shows you the code you wrote without hiding the machinery that makes it cheap.

