📖 Scenario: Imagine you are creating a simple calculator that can remember a number and add it to other numbers later.
🎯 Goal: You will build a small program that uses a lambda function to remember a number (capture it) and add it to new numbers when called.
📋 What You'll Learn
Create an integer variable called baseNumber with the value 10
Create a lambda function called addBase that takes an integer parameter x and returns the sum of baseNumber and x
Call the lambda function addBase with the value 5 and store the result in a variable called result
Print the value of result
💡 Why This Matters
🌍 Real World
Closures like this are useful when you want to create small functions that remember some data without needing to pass it every time.
💼 Career
Understanding closures helps in writing clean, reusable code in many programming jobs, especially when working with events, callbacks, or functional programming styles.
Progress0 / 4 steps
1
Create the base number
Create an integer variable called baseNumber and set it to 10.
C Sharp (C#)
Hint
Use int baseNumber = 10; to create the variable.
2
Create the lambda function with capture
Create a lambda function called addBase that takes an integer parameter x and returns the sum of baseNumber and x.
C Sharp (C#)
Hint
Use Func<int, int> and a lambda expression like x => baseNumber + x.
3
Call the lambda function
Call the lambda function addBase with the value 5 and store the result in a variable called result.
C Sharp (C#)
Hint
Call addBase(5) and assign it to result.
4
Print the result
Print the value of the variable result using Console.WriteLine.
C Sharp (C#)
Hint
Use Console.WriteLine(result); to show the output.
Practice
(1/5)
1.
What does it mean when a lambda expression captures a variable in C#?
easy
A. The lambda deletes the variable after execution.
B. The lambda remembers and uses the variable from outside its own code block.
C. The lambda creates a new variable with the same name inside its code.
D. The lambda can only use variables declared inside it.
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 B
The lambda should use the external variable count without redeclaring it.
Step 2: Check syntax correctness
() => count++; uses an empty parameter list and increments the external count variable correctly.
Final Answer:
() => count++; -> Option A
Quick Check:
Empty params and external variable increment [OK]
Hint: Use empty parentheses to capture external variables [OK]
Common Mistakes:
Trying to redeclare captured variable inside lambda
Using lambda parameters instead of capturing
Incorrect lambda syntax with parameters
3.
What is the output of this C# code?
int x = 5;
Func<int> f = () => x * 2;
x = 10;
Console.WriteLine(f());
medium
A. Compile error
B. 10
C. 5
D. 20
Solution
Step 1: Understand variable capture behavior
The lambda captures the variable x by reference, not by value.
Step 2: Evaluate the lambda call after changing x
Since x was changed to 10 before calling f(), the lambda returns 10 * 2 = 20.
Final Answer:
20 -> Option D
Quick Check:
Captured variable reflects latest value [OK]
Hint: Captured variables reflect current value when lambda runs [OK]
Common Mistakes:
Assuming lambda captures variable value at creation time
Expecting output 5 or 10 instead of 20
Thinking code causes compile error
4.
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);
medium
A. The variable i is captured incorrectly, causing unexpected results.
B. The variable total cannot be captured by the lambda.
C. The lambda syntax is invalid and causes a compile error.
D. The list actions cannot store lambdas.
Solution
Step 1: Analyze variable capture in loop
The lambda captures the loop variable i by reference, so all lambdas share the same i.
Step 2: Effect on final output
After the loop, i is 3, so each lambda adds 3 to total, resulting in total = 9 instead of expected 0+1+2=3.
Final Answer:
The variable i is captured incorrectly, causing unexpected results. -> Option A
Quick Check:
Loop variable capture causes bugs [OK]
Hint: Loop variables captured by reference cause bugs [OK]
Common Mistakes:
Thinking total can't be captured
Believing lambda syntax is wrong
Assuming list can't hold lambdas
5.
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());
hard
A. actions.Add((int i) => Console.WriteLine(i));
B. actions.Add(() => Console.WriteLine(i));
C. int copy = i; actions.Add(() => Console.WriteLine(copy));
D. actions.Add(() => Console.WriteLine(0));
Solution
Step 1: Understand loop variable capture problem
Directly capturing i causes all lambdas to print the final value of i (3).
Step 2: Use a local copy to capture each index
Declaring copy = i inside 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 C
Quick Check:
Use local copy to capture loop variable [OK]
Hint: Copy loop variable inside loop before lambda [OK]
Common Mistakes:
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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.