Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Lambda with captures (closures) in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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());
A20
BCompilation error
C10
D5
Attempts:
2 left
💡 Hint
Remember that lambdas capture variables by reference, not by value.
❓ Predict Output
intermediate
2: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();
A0 1 2
BCompilation error
C0 0 0
D3 3 3
Attempts:
2 left
💡 Hint
Consider how the loop variable i is captured by the lambdas.
🔧 Debug
advanced
2: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();
AThe list actions is cleared before printing, so output is from a default value.
BThe lambda syntax is incorrect and causes all lambdas to share the same output.
CThe variable i is captured by reference, so all lambdas see the final value 3.
DThe loop variable i is copied inside the lambda, but the copy is overwritten.
Attempts:
2 left
💡 Hint
Think about how variables in loops are captured by lambdas in C#.
📝 Syntax
advanced
2: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();
Aactions.Add(() => Console.Write(i + " "));
B
int copy = i;
actions.Add(() =&gt; Console.Write(copy + " "));
Cactions.Add(delegate { Console.Write(i + " "); });
Dactions.Add(() => Console.Write((i + 1) + " "));
Attempts:
2 left
💡 Hint
Try creating a new variable inside the loop to hold the current value.
🚀 Application
expert
3: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));
A3 unique values: 5,6,7
B3 unique values: 2,3,4
C1 unique value: 8
D1 unique value: 6
Attempts:
2 left
💡 Hint
Remember which variables are captured by reference and which by value.

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

  1. Step 1: Understand lambda captures

    A lambda can use variables declared outside its own code block by capturing them.
  2. Step 2: Effect of capturing

    This means the lambda remembers the variable's value and can use or modify it later.
  3. Final Answer:

    The lambda remembers and uses the variable from outside its own code block. -> Option B
  4. Quick Check:

    Lambda captures = remembers outside variables [OK]
Hint: Captured variables come from outside the lambda [OK]
Common Mistakes:
  • Thinking lambda creates new variables instead of capturing
  • Assuming variables are deleted after lambda runs
  • Believing lambdas can't use outside variables
2.

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 = ?;
easy
A. () => count++;
B. (int count) => count++;
C. () => { int count = 0; count++; };
D. count => count + 1;

Solution

  1. Step 1: Identify lambda capturing external variable

    The lambda should use the external variable count without redeclaring it.
  2. Step 2: Check syntax correctness

    () => count++; uses an empty parameter list and increments the external count variable correctly.
  3. Final Answer:

    () => count++; -> Option A
  4. 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

  1. Step 1: Understand variable capture behavior

    The lambda captures the variable x by reference, not by value.
  2. Step 2: Evaluate the lambda call after changing x

    Since x was changed to 10 before calling f(), the lambda returns 10 * 2 = 20.
  3. Final Answer:

    20 -> Option D
  4. 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

  1. Step 1: Analyze variable capture in loop

    The lambda captures the loop variable i by reference, so all lambdas share the same i.
  2. 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.
  3. Final Answer:

    The variable i is captured incorrectly, causing unexpected results. -> Option A
  4. 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

  1. Step 1: Understand loop variable capture problem

    Directly capturing i causes all lambdas to print the final value of i (3).
  2. 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.
  3. Final Answer:

    int copy = i; actions.Add(() => Console.WriteLine(copy)); -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard