Challenge - 5 Problems
Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of lambda capturing a variable
What is the output of this C# code that uses a lambda capturing a variable?
C Sharp (C#)
int x = 5; Func<int> f = () => x * 2; x = 10; Console.WriteLine(f());
Attempts:
2 left
💡 Hint
Remember that lambdas capture variables by reference, not by value.
✗ Incorrect
The lambda captures the variable x by reference. When f() is called, x is 10, so the output is 20.
❓ Predict Output
intermediate2:00remaining
Output of multiple lambdas capturing loop variable
What is the output of this C# code with lambdas capturing a loop variable?
C Sharp (C#)
var actions = new List<Action>(); for (int i = 0; i < 3; i++) { actions.Add(() => Console.Write(i + " ")); } foreach (var action in actions) action();
Attempts:
2 left
💡 Hint
Consider how the loop variable i is captured by the lambdas.
✗ Incorrect
The lambdas capture the variable i by reference. After the loop, i is 3, so all lambdas print 3.
🔧 Debug
advanced2:00remaining
Why does this lambda capture cause unexpected output?
This code intends to print 0, 1, 2 but prints 3, 3, 3 instead. Why?
C Sharp (C#)
var actions = new List<Action>(); for (int i = 0; i < 3; i++) { actions.Add(() => Console.Write(i + " ")); } foreach (var action in actions) action();
Attempts:
2 left
💡 Hint
Think about how variables in loops are captured by lambdas in C#.
✗ Incorrect
In C#, the loop variable i is captured by reference by all lambdas, so they all see the final value after the loop ends.
📝 Syntax
advanced2:00remaining
Which lambda correctly captures a local variable inside a loop?
Which option correctly captures the loop variable so that each lambda prints 0, 1, and 2 respectively?
C Sharp (C#)
var actions = new List<Action>(); for (int i = 0; i < 3; i++) { // capture i correctly here } foreach (var action in actions) action();
Attempts:
2 left
💡 Hint
Try creating a new variable inside the loop to hold the current value.
✗ Incorrect
Creating a new variable copy inside the loop captures the current value correctly for each lambda.
🚀 Application
expert3:00remaining
How many unique values are captured by these lambdas?
Consider this code snippet. How many unique values are printed when invoking all lambdas in the list?
C Sharp (C#)
var funcs = new List<Func<int>>(); int x = 1; for (int i = 0; i < 3; i++) { int y = i; funcs.Add(() => x + y); } x = 5; var results = funcs.Select(f => f()).ToList(); Console.WriteLine(string.Join(",", results));
Attempts:
2 left
💡 Hint
Remember which variables are captured by reference and which by value.
✗ Incorrect
x is captured by reference by all lambdas and is changed to 5 before invocation. Each y is a distinct local variable per iteration (y=0,1,2), so the lambdas return 5+0=5, 5+1=6, 5+2=7. Three unique values: 5,6,7.