Lambdas with captures let you create small functions that remember values from outside their own code. This helps keep related data and behavior together.
Lambda with captures (closures) in C Sharp (C#)
var lambda = () => expression; // or with captures int x = 5; Func<int> lambdaWithCapture = () => x + 10;
Lambdas can access variables from the surrounding method or scope.
These captured variables are kept alive as long as the lambda exists.
a and adds 5 to it.int a = 3; Func<int> addFive = () => a + 5; Console.WriteLine(addFive());
count and increases it each time it runs.int count = 0; Action increment = () => count++; increment(); increment(); Console.WriteLine(count);
prefix to create a greeting.string prefix = "Hello"; Func<string, string> greet = name => prefix + ", " + name + "!"; Console.WriteLine(greet("Alice"));
This program shows a lambda that captures baseNumber. When baseNumber changes, the lambda uses the new value.
using System; class Program { static void Main() { int baseNumber = 10; Func<int, int> addBase = x => x + baseNumber; Console.WriteLine(addBase(5)); // 15 baseNumber = 20; // Change captured variable Console.WriteLine(addBase(5)); // 25 } }
Captured variables are not copied; the lambda uses the original variable.
Changing the captured variable affects all lambdas that capture it.
Be careful with captured variables in loops to avoid unexpected results.
Lambdas with captures remember variables from outside their code.
This helps write small, flexible functions without extra classes.
Captured variables stay alive as long as the lambda needs them.
Practice
What does it mean when a lambda expression captures a variable in C#?
Solution
Step 1: Understand lambda captures
A lambda can use variables declared outside its own code block by capturing them.Step 2: Effect of capturing
This means the lambda remembers the variable's value and can use or modify it later.Final Answer:
The lambda remembers and uses the variable from outside its own code block. -> Option BQuick Check:
Lambda captures = remembers outside variables [OK]
- Thinking lambda creates new variables instead of capturing
- Assuming variables are deleted after lambda runs
- Believing lambdas can't use outside variables
Which of the following is the correct syntax to declare a lambda that captures an external variable count and increments it?
int count = 0; var increment = ?;
Solution
Step 1: Identify lambda capturing external variable
The lambda should use the external variablecountwithout redeclaring it.Step 2: Check syntax correctness
() => count++; uses an empty parameter list and increments the externalcountvariable correctly.Final Answer:
() => count++; -> Option AQuick Check:
Empty params and external variable increment [OK]
- Trying to redeclare captured variable inside lambda
- Using lambda parameters instead of capturing
- Incorrect lambda syntax with parameters
What is the output of this C# code?
int x = 5; Func<int> f = () => x * 2; x = 10; Console.WriteLine(f());
Solution
Step 1: Understand variable capture behavior
The lambda captures the variablexby reference, not by value.Step 2: Evaluate the lambda call after changing
Sincexxwas changed to 10 before callingf(), the lambda returns 10 * 2 = 20.Final Answer:
20 -> Option DQuick Check:
Captured variable reflects latest value [OK]
- Assuming lambda captures variable value at creation time
- Expecting output 5 or 10 instead of 20
- Thinking code causes compile error
Identify the error in this code snippet involving a lambda with captures:
int total = 0;
var actions = new List<Action>();
for (int i = 0; i < 3; i++) {
actions.Add(() => total += i);
}
actions.ForEach(a => a());
Console.WriteLine(total);Solution
Step 1: Analyze variable capture in loop
The lambda captures the loop variableiby reference, so all lambdas share the samei.Step 2: Effect on final output
After the loop,iis 3, so each lambda adds 3 tototal, resulting in total = 9 instead of expected 0+1+2=3.Final Answer:
The variableiis captured incorrectly, causing unexpected results. -> Option AQuick Check:
Loop variable capture causes bugs [OK]
- Thinking total can't be captured
- Believing lambda syntax is wrong
- Assuming list can't hold lambdas
You want to create a list of lambdas that each print their own index from 0 to 2. Which code correctly captures the index variable?
var actions = new List<Action>();
for (int i = 0; i < 3; i++) {
// Fill in here
}
actions.ForEach(a => a());Solution
Step 1: Understand loop variable capture problem
Directly capturingicauses all lambdas to print the final value ofi(3).Step 2: Use a local copy to capture each index
Declaringcopy = iinside the loop creates a new variable for each iteration, which the lambda captures correctly.Final Answer:
int copy = i; actions.Add(() => Console.WriteLine(copy)); -> Option CQuick Check:
Use local copy to capture loop variable [OK]
- Capturing loop variable directly causing all lambdas to print same value
- Trying to add lambda with parameter in Add method
- Hardcoding constant instead of variable
Ready to prove it?
Pass the test and this pattern moves unknown
