0
0
C Sharp (C#)programming~10 mins

Lambda with captures (closures) in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lambda with captures (closures)
Define variable x
Create lambda capturing x
Store lambda in a delegate
Change x or call lambda
Lambda uses captured x value
Output result
This flow shows how a lambda captures a variable from its surrounding scope and uses it later when called.
Execution Sample
C Sharp (C#)
int x = 5;
Func<int> f = () => x + 10;
x = 7;
int result = f();
Console.WriteLine(result);
This code creates a lambda that adds 10 to x, then changes x, calls the lambda, and prints the result.
Execution Table
StepActionVariable xLambda fResultOutput
1Initialize x5nullnullnull
2Create lambda f capturing x5() => x + 10nullnull
3Change x to 77() => x + 10nullnull
4Call lambda f()7() => x + 1017null
5Print result7() => x + 101717
💡 Program ends after printing the result 17
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
x55777
resultnullnullnull1717
Key Moments - 2 Insights
Why does the lambda see the updated value of x (7) instead of the original (5)?
Because the lambda captures the variable x itself, not just its value at creation. So when x changes before calling the lambda (step 3), the lambda uses the current value (step 4).
What if we changed x after calling the lambda? Would the lambda output change?
No, because the lambda uses the value of x at the time it is called. Changes after calling do not affect past results (see step 4 and 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x when the lambda f is called at step 4?
A5
B7
Cnull
D17
💡 Hint
Check the 'Variable x' column at step 4 in the execution_table.
At which step is the lambda f created capturing x?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look for the action 'Create lambda f capturing x' in the execution_table.
If we changed x to 10 after step 4 but before printing, what would the output be?
A17
B20
C10
Dnull
💡 Hint
The lambda was already called at step 4 producing 17; changing x after does not affect that result.
Concept Snapshot
Lambda with captures (closures) in C#:
- Lambdas can capture variables from their surrounding scope.
- They capture the variable itself, not just its value at creation.
- When called, the lambda uses the current value of captured variables.
- Useful for deferred execution and preserving context.
- Syntax: Func<int> f = () => x + 10;
Full Transcript
This example shows how a lambda in C# captures a variable from outside its body. We start with x = 5. Then we create a lambda f that adds 10 to x. Next, we change x to 7. When we call f(), it uses the current value of x, which is 7, so the result is 17. Finally, we print 17. This demonstrates that lambdas capture variables by reference, not by value, so they see the latest value when called.