1.13 — Lambda Expressions and Closures¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.12 Events · Next: 1.14 Extension methods
Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- A lambda is a short way to write a method inline.
x => x * 2is a whole method. - A closure happens when a lambda uses a variable from the code around it. The compiler quietly moves that variable onto the heap so the lambda can still reach it later.
- Closures capture the variable itself, not its value at that moment. That is the trap, and it bites hardest inside loops.
The concept¶
A lambda is just a method without a name, written where you need it.
// A normal method
static bool IsExpensive(Order o) { return o.Total > 100; }
// The same thing as a lambda
o => o.Total > 100
Read => as "goes to" or "becomes". So o => o.Total > 100 reads as "an order becomes
whether its total is over 100".
A closure is what happens when a lambda reaches out and uses a variable from outside itself. The lambda "closes over" that variable — it keeps hold of it.
This sounds harmless. It is where the interesting behaviour, and the classic bug, comes from.
How it works¶
Lambda syntax¶
() => 42 // no parameters
x => x * 2 // one parameter, brackets optional
(x, y) => x + y // two parameters, brackets required
(int x, int y) => x + y // explicit types when inference fails
x => // multiple statements need braces
{
var doubled = x * 2;
return doubled + 1;
}
What a closure actually does¶
Here is a lambda that uses a variable from outside:
threshold is a local variable. Normally, when the method it lives in finishes, it
disappears. But the lambda might be called much later, so the variable has to survive.
The compiler solves this by secretly rewriting your code. It creates a hidden class,
moves threshold into it as a field, and makes both your method and the lambda use that
field instead of a local variable.
Roughly, the compiler turns the code above into something like this:
// Compiler-generated, you never see this
class HiddenClosure
{
public int threshold;
public bool IsExpensive(Order o) => o.Total > this.threshold;
}
var closure = new HiddenClosure();
closure.threshold = 100;
Func<Order, bool> isExpensive = closure.IsExpensive;
Two consequences follow from this, and both matter:
- There is a heap allocation. Every closure creates one of these hidden objects.
- The lambda shares the variable — it does not copy it. Both your method and the lambda are now reading and writing the same field.
That second point is the whole trap.
The trap: capturing a variable, not a value¶
var actions = new List<Action>();
for (int i = 0; i < 3; i++)
{
actions.Add(() => Console.WriteLine(i));
}
foreach (var a in actions) a();
What do you expect? Most people say 0 1 2.
In older C# the answer was 3 3 3.
Why? Because there is only one i variable for the whole loop. All three lambdas
captured that same variable. By the time you ran them, the loop had finished and i had
reached 3. All three read the same field, and that field said 3.
The fix is to give each iteration its own variable:
for (int i = 0; i < 3; i++)
{
int copy = i; // a NEW variable each iteration
actions.Add(() => Console.WriteLine(copy));
}
// Now prints 0 1 2
Important modern update: C# 5 changed foreach so that the loop variable is a fresh
variable each iteration. So foreach is safe now:
But a classic for loop still has one variable, so for loops still have this
problem. If you remember one thing: foreach is safe, for is not.
Avoiding the allocation¶
If a lambda does not use anything from around it, the compiler does not need a closure at all — it can cache a single instance and reuse it forever.
// No capture — free, cached by the compiler
items.Where(x => x.IsActive);
// Captures 'minimum' — allocates a closure object every time this runs
items.Where(x => x.Total > minimum);
In a hot loop you can avoid the allocation by passing the value through instead, when the API supports it:
// Some APIs take a 'state' parameter exactly for this reason
cache.GetOrCreate(key, state: minimum, static (entry, min) => Compute(min));
The static keyword on a lambda (C# 9+) tells the compiler "this lambda must not capture
anything". If you accidentally capture something, you get a compile error instead of a
silent allocation. It is a good habit in performance-sensitive code:
Code¶
A realistic version of the loop bug, which does show up in real code:
// BUG: all tasks use the same 'i'
var tasks = new List<Task>();
for (int i = 0; i < files.Count; i++)
{
tasks.Add(Task.Run(() => ProcessFile(files[i])));
// By the time these run, i == files.Count
// → IndexOutOfRangeException, or every task processes the same file
}
await Task.WhenAll(tasks);
// FIXED: each iteration captures its own copy
var tasks = new List<Task>();
for (int i = 0; i < files.Count; i++)
{
var index = i; // fresh variable per iteration
tasks.Add(Task.Run(() => ProcessFile(files[index])));
}
await Task.WhenAll(tasks);
// BETTER: foreach avoids the whole problem, and reads more clearly
var tasks = files.Select(file => Task.Run(() => ProcessFile(file)));
await Task.WhenAll(tasks);
This bug is especially nasty because it is timing-dependent. If the tasks happen to run fast enough, you might get correct results in testing and wrong results in production.
Interview questions¶
Q: What is a closure?
It is what happens when a lambda or anonymous method uses a variable from the scope around it. The compiler cannot let that variable disappear when the method returns, because the lambda might run later. So it generates a hidden class, moves the variable into it as a field, and rewrites both the outer method and the lambda to use that field. The result is that the lambda and the surrounding code share one variable rather than each having a copy.
Q: What is the classic closure bug in a loop?
If you create lambdas inside a for loop and capture the loop variable, every lambda
captures the same variable, not its value at that moment. So when you run them
afterwards, they all see the final value. A loop from 0 to 2 gives you three lambdas that
all print 3. The fix is to copy the loop variable into a new variable inside the loop body,
so each iteration gets its own. Worth adding that C# 5 changed foreach so its variable is
fresh each iteration — so foreach is safe, but a plain for loop still has the problem.
Q: Do closures have a performance cost?
Yes. Every time a lambda captures something, a hidden object gets allocated on the heap to
hold the captured variables, plus a delegate object. In normal code that is irrelevant, but
in a hot path called thousands of times per second it adds real garbage collection
pressure. A lambda that captures nothing is free, because the compiler caches a single
instance. You can mark a lambda static to make the compiler prove it captures nothing.
Q: What does static on a lambda do?
It tells the compiler the lambda is not allowed to capture any variable from the surrounding scope. If you try, you get a compile error. It is useful in performance-critical code because it turns an accidental allocation into something the compiler catches for you, and it documents the intent clearly.
Traps ⚠️¶
- Capturing a
forloop variable. All lambdas share one variable.foreachis safe since C# 5;foris not. - The captured variable is shared both ways. If the outer code changes it after the lambda is created, the lambda sees the new value.
- A closure keeps the whole captured object alive. If a lambda captures
thisimplicitly by using a field, it keeps the entire containing object from being collected. That is a common leak in event handlers — see 1.12. - Closures allocate. Two objects, in fact — the closure and the delegate. Fine normally, expensive in a tight loop.
- Capturing a
ref,out, orinparameter is not allowed. Nor is capturing aSpan<T>, because those cannot live on the heap. - Async lambdas that capture large objects hold them for the whole operation, not just
until the first
await.
Related¶
- 1.11 Delegates — what a lambda actually becomes
- 1.5 Static local functions — the same allocation-avoidance idea
- 1.12 Events — lambda handlers you cannot unsubscribe
- 2.5 LINQ — lambdas everywhere
- 2.7 Expression trees — when a lambda becomes data rather than code
- 19.13 Reducing allocations — closures in hot paths