skip to content

In C#, what does the compiler generate when a lambda captures a local variable, and why do two lambdas capturing it see each other's writes?

level: middleimportance: should knowfreq 60%

answer

  1. the local stops being a local
  2. a compiler-generated class
  3. one object per scope
  4. the delegate's Target

basics

~20 s

The compiler moves a captured local into a field of a generated closure class, one instance per scope entry. The method and every lambda in that scope use that one field, so any write is seen by all.

solid answer

~40 s

When a lambda reads or writes a local, the C# compiler **hoists** that local into a field of a compiler-generated closure class (named like `<>c__DisplayClass0_0`), creates one instance when execution enters the local's scope, and turns the lambda into an instance method of that class. The delegate's `Target` is that object. The enclosing method stops using a stack slot and reads and writes the field too. Every lambda in the same scope shares the same instance, so `raise` incrementing `threshold` is visible to `isLarge`, and `isLarge.Target == raise.Target` is `true`. The captured variable lives as long as any delegate referencing that object. A `ref`, `out` or `in` parameter cannot be captured (CS1628), because a heap field cannot hold a reference to the caller's variable.

code

csharp · 10 lines
csharp
int threshold = 100;
Func<int, bool> isLarge = amount => amount > threshold;
Action raise = () => threshold += 50;

Console.WriteLine(isLarge(120));                  // True
raise();
Console.WriteLine(threshold);                     // 150: raise wrote the shared variable
Console.WriteLine(isLarge(120));                  // False: isLarge reads that same variable
Console.WriteLine(isLarge.Target == raise.Target); // True: both delegates point at one closure object
Console.WriteLine(isLarge.Target!.GetType().Name);  // the compiler-generated closure class

go deeper

for a junior

Recall that a lambda uses the variable itself, so a change made after the lambda was created is visible when it runs.

for a middle

Explain the closure class: captured locals become fields of one compiler-generated object per scope, shared by the method and every lambda in that scope.

for a senior

Use the per-scope grouping to explain retained memory behind a stored callback, and know why ref parameters and ref struct locals cannot be captured.

for a principal

Weigh the readability of captured state against explicit state passed as arguments in shared code, where hidden captures make lifetimes hard to reason about.

## From local variable to field A C# local variable normally lives in the method's stack frame and disappears when the method returns. A lambda may run much later, so a local it uses cannot stay there. The compiler solves this by **rewriting the method**: 1. It generates a private nested class, the **closure class** (Roslyn names it like `<>c__DisplayClass0_0`; the name is an implementation detail). 2. Each captured local becomes a **public field** of that class. 3. When execution enters the scope that declares the captured locals, the method allocates **one instance** of the class. 4. Every use of the local, in the method and in the lambdas, becomes a read or write of that instance's field. 5. Each lambda becomes an **instance method** of the closure class, and the delegate created for it has that instance as its `Target`. Nothing is copied at capture time. The method and the lambdas all use one storage location. ## Why two lambdas see each other's writes Take a pricing screen with two lambdas over one local: ```csharp int threshold = 100; Func<int, bool> isLarge = amount => amount > threshold; Action raise = () => threshold += 50; ``` Both lambdas live in the same scope, so both become methods of **one** closure object, and both read the same `threshold` field. After `raise()`, `threshold` is 150 in the method and in `isLarge`, so `isLarge(120)` changes from `True` to `False`. `isLarge.Target == raise.Target` returns `True`: the two delegates point at one object. | Step | What is shared | |---|---| | `threshold = 100` in the method | writes the closure field | | `raise()` | writes the same field | | `isLarge(120)` | reads the same field at call time | ## One closure object per scope, not per lambda The compiler groups captured variables **by the scope that declares them**, not by the lambda that uses them. Two consequences matter in production code: - **Shared lifetime.** If one lambda captures a large `byte[]` and another lambda in the same scope captures only a small counter, both locals sit in the same closure object. Keeping only the counter lambda alive (stored in a cache or subscribed to a long-lived event) keeps the array reachable too. On the .NET 10 SDK's compiler, a weak reference to such an array still reports it alive after a full collection. - **Nested scopes get their own class.** A local declared inside a loop body or an inner block gets a closure object created on each entry to that block; it holds a reference to the outer scope's closure object when lambdas use both. The reachability rule itself, that a captured variable lives as long as a delegate that references it, is what Microsoft's documentation states; how Roslyn groups variables into classes is its implementation, which is what you observe in a decompiler or with `Target.GetType()`. ## What cannot be captured Because a captured variable becomes a heap field, the compiler rejects captures that a field cannot represent: - a `ref`, `out` or `in` **parameter** of the enclosing method: **CS1628**, "Cannot use ref, out, or in parameter 'counter' inside an anonymous method, lambda expression, query expression, or local function"; - a **ref local**, and a local of a ref struct type such as `Span<int>`: the compiler reports **CS8175** on the .NET 10 SDK; - nothing at all, when the lambda is marked `static` (C# 9): **CS8820** for a local or parameter and **CS8821** for `this`. The usual workaround for a `ref` parameter is to copy it into a local, capture the local and write the result back after the lambda runs. ## Capturing this A lambda that uses an instance field or method captures `this`, not the field. If it captures no locals, the compiler emits it as an instance method of the containing class and the delegate's `Target` is the object itself; no closure class is needed. The field is read through `this` every time, so the lambda sees later changes to it. ## How interviewers probe it - They show two lambdas over one local and ask what the second prints after the first writes. - They ask why a `ref` parameter cannot be used in a lambda. - They ask what a stored callback keeps alive, and expect the answer to name the whole closure object, not just the variables that lambda mentions.

  • In C#, one long-lived lambda captures only a small counter, but a large array captured by another lambda in the same method is never collected. Why?
    The compiler creates one closure object per scope, holding every local any lambda in that scope captures. The long-lived delegate's `Target` is that object, so it keeps the array field reachable even though its own lambda never mentions the array. Moving the array's capture into a separate method, or into an inner block, gives it a separate closure object.
  • In C#, how do you use a ref parameter's value inside a lambda?
    Copy it into an ordinary local, let the lambda capture the local, and assign the local back to the `ref` parameter after the lambda has run if the method must report the change. The lambda then works on the closure field, and the method controls when the caller's variable is updated.
  • In C#, does a lambda that only reads a field of its class allocate a closure object?
    No. With no captured locals, the compiler emits the lambda as an instance method of the class itself, and the delegate's `Target` is `this`. Each evaluation still allocates a new delegate, and the field is read through `this` when the lambda runs, so it sees later changes.

  • Says a lambda copies captured locals into the delegate when it is created.
  • Thinks each lambda gets a private closure object even when they share a scope.
  • Believes captured locals stay on the stack and the lambda reads the frame.
  • Claims a lambda can capture a ref parameter if it only reads it.
  • Says a lambda that reads a field captures a copy of that field.