Lambda expressions and captures
Lambda expressions and captures
A lambda is a concise anonymous function. When it uses a variable declared outside itself, the variable can remain available through a closure even after the surrounding method returns.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; outputs are predictions pending compilation.
Write expression and statement lambdas
The syntax is parameters => expression or parameters => { statements }. The target delegate determines compatible inputs and result. An expression lambda can return its expression; a block lambda returning a value uses return. Lambdas are not executed just by creating them. The older delegate (...) { ... } anonymous method syntax is also available.
using System;Func<int, int> square = x => x * x;Func<int, int> clamp = x => { if (x < 0) return 0; return x; };Console.WriteLine(square(4));Console.WriteLine(clamp(-3));Console.WriteLine(clamp(7));The delegate type provides the parameter and result types. The second body contains explicit statements and returns.
Expected output (reasoned, not executed):
1607Captured variables are not frozen values
A closure can retain access to a local variable, including subsequent assignments. A captured variable can outlive the method that declared it. Separate calls to a factory method have distinct local variables; multiple delegates from the same call may share a variable. Capturing can retain referenced objects and may require allocation; exact allocation behavior depends on compiler and runtime.
using System;var first = MakeCounter();var second = MakeCounter();Console.WriteLine(first());Console.WriteLine(first());Console.WriteLine(second());static Func<int> MakeCounter(){ int count = 0; return () => ++count;}Each MakeCounter call creates its own count; the returned delegate can update that variable after the call returns.
Expected output (reasoned, not executed):
121Avoid accidentally capturing a shared loop variable
A for loop variable declared in its initializer is shared across iterations of that loop. Lambdas referencing it can all observe its final value if invoked later. Declare a fresh local inside the body to capture a separate value per iteration. Modern C# foreach has a distinct iteration variable per iteration. Use a static lambda to prevent capture of outer locals or instance state; static members and constants can still be referenced.
using System;using System.Collections.Generic;var shared = new List<Func<int>>();var separate = new List<Func<int>>();for (int i = 0; i < 3; i++){ shared.Add(() => i); int copy = i; separate.Add(() => copy);}foreach (var read in shared) Console.WriteLine(read());foreach (var read in separate) Console.WriteLine(read());Func<int, int> triple = static x => x * 3;Console.WriteLine(triple(2));All shared callbacks read i after the loop. Each copy belongs to a different body iteration. The static lambda needs no capture.
Expected output (reasoned, not executed):
3330126Common mistakes and edge cases
Do not assume a capture copies a value when the delegate is created. Avoid unnecessarily retaining large objects through closures. A static lambda does not guarantee no allocations or side effects. Default lambda parameters and attributes have version-specific rules; this lesson uses ordinary C# 14-compatible forms without relying on those features.
Practice and next steps
Build three callbacks in a for loop for IDs 10, 11, 12. Invoke them only after the loop. First capture the loop variable, then repair the result using a fresh local. Also create two independent counters and call each twice.
Next: Func, Action and Predicate.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lambda expressions and captures — knowledge check
Apply the lesson concepts to the following scenarios.
When is the body of an ordinary lambda executed?
A lambda captures x, initially 2, and x later becomes 5. What does `() => x` return?
Three callbacks capture a for loop i that ends at 3. What do they return afterward?
How do you prevent capture of an enclosing local by a lambda?
Two calls to MakeCounter return independent delegates. Why?