In C#, why do callbacks created in a for loop all see the counter's final value, while a foreach loop gives each its own?
answer
- how many counter variables exist
- captured variable, not captured value
- what changed in C# 5
- a copy inside the loop body
basics
~20 sA for loop declares its counter once, and every lambda captures that one variable, so all callbacks see its final value. Since C# 5 a foreach loop declares a fresh iteration variable per pass, so each callback keeps its own element.
solid answer
~40 sA lambda captures the **variable**, not its value at creation. In `for (int i = 0; i < 3; i++) clicks.Add(() => Console.Write(i));` there is exactly one `i`, declared outside the body, so the compiler puts it in one closure object that all three delegates share; when they run after the loop, `i` is 3, the value that ended the loop, so each prints 3. C# 5 changed only `foreach`: its iteration variable is now logically declared inside the loop, so each pass gets a new variable and a new closure object. The fix for `for` is to copy the counter into a local declared inside the body, `int index = i;`, and capture `index`.
code
csharp · 25 linesvar clicks = new List<Action>();
for (int i = 0; i < 3; i++)
{
clicks.Add(() => Console.Write($"button {i}; ")); // one shared i
}
foreach (var click in clicks) click();
Console.WriteLine(); // button 3; button 3; button 3;
var fixedClicks = new List<Action>();
for (int i = 0; i < 3; i++)
{
int index = i; // a new variable per iteration
fixedClicks.Add(() => Console.Write($"button {index}; "));
}
foreach (var click in fixedClicks) click();
Console.WriteLine(); // button 0; button 1; button 2;
var labels = new[] { "Save", "Open", "Close" };
var foreachClicks = new List<Action>();
foreach (var label in labels) // fresh per iteration since C# 5
{
foreachClicks.Add(() => Console.Write($"{label}; "));
}
foreach (var click in foreachClicks) click();
Console.WriteLine(); // Save; Open; Close;go deeper
Recall that a lambda captures the variable itself, so callbacks created in a for loop all print the counter's final value.
Explain why a for loop has one counter variable while foreach has one per pass since C# 5, and show the body-local copy that fixes it.
Recognise the same sharing in tasks, timers and handlers started inside loops, where the printed value depends on timing, and fix it in review.
Decide whether an analyzer or review rule should flag lambdas that capture a for counter, weighing noise against how often the bug ships.
## The symptom A screen builds three buttons in a loop and registers a click callback for each: ```csharp for (int i = 0; i < 3; i++) { clicks.Add(() => Console.Write($"button {i}; ")); } ``` Running the callbacks afterwards prints `button 3; button 3; button 3;`. Not 0, 1, 2, and not even 2: **3**, the value that made `i < 3` false and ended the loop. ## A lambda captures a variable When a lambda uses a local variable of the enclosing method, the C# compiler moves that variable into a field of a compiler-generated **closure class** and makes both the method and the lambda read and write that field. Two consequences follow: - the lambda sees the variable's **current** value when it runs, not the value it had when the lambda was created; - every lambda that captured the same variable shares the **same** field in the same closure object. So the question is always: *how many variables are there?* ## How many variables each loop declares | Loop | Where the variable lives | Variables per loop | What the callbacks print | |---|---|---|---| | `for (int i = ...)` | declared once, before the first iteration | **one** | the final value, three times | | `foreach (var label in labels)` (C# 5 and later) | declared inside each iteration | **one per pass** | each its own element | | `for` with `int index = i;` in the body | `index` is declared inside the body | **one per pass** | 0, 1, 2 | The `for` statement's initializer runs once, so its `i` is a single variable that the loop increments in place. The compiler creates one closure object for it before the loop starts, and all three delegates point at that object. ## What C# 5 changed, and what it did not Before **C# 5**, the `foreach` iteration variable was also declared once, outside the loop, and `foreach` had the same bug. C# 5 changed the language so that a `foreach` iteration variable is **logically inside the loop body**: each pass gets a fresh variable, and a lambda created in that pass captures that pass's variable. The `for` loop was not changed: its counter is one variable that the loop's condition and iterator read and write across passes. So on any current compiler: 1. `foreach` + lambda: each callback sees its own element. 2. `for` + lambda capturing the counter: every callback sees the final value. 3. `for` + lambda capturing a local declared in the body: each callback sees its own copy. ## The fix Declare a new variable inside the body and capture that instead: ```csharp for (int i = 0; i < 3; i++) { int index = i; // a new variable on every pass fixedClicks.Add(() => Console.Write($"button {index}; ")); } ``` Each pass now allocates its own closure object holding its own `index`. Alternatives that work for the same reason: - loop with `foreach` over the items or over `Enumerable.Range(0, 3)`; - pass the index as an argument to a method that creates the callback, so the parameter is a new variable per call. Marking the lambda `static` does **not** fix it: a static lambda may not capture `i` at all, and the compiler reports **CS8820**. ## Where else it bites - **Deferred work.** Any callback that runs later (a timer, a task started in the loop, an event handler) sees the shared counter's value at the moment it runs, which may be a middle value if the loop is still running. - **Writes through the closure.** A lambda that does `i++` changes the loop's own counter, because it is the same variable. - **Queries built in a loop.** A deferred LINQ query that captures the counter is read when it is enumerated, which is covered with deferred execution. ## How interviewers probe it - They show the three-line loop and ask what prints, and expect **3**, not 2. - They ask whether rewriting it with `foreach` changes the output, and in which C# version that became true. - They ask for the smallest fix and why it works: a variable declared inside the body is a new variable per iteration.
- In C#, if the for-loop callbacks are started as tasks inside the loop, what values can they print?Any value the shared counter holds when each task reads it: a task that runs before the loop finishes may print a middle value, and later ones print the final value. The output is no longer deterministic, because the tasks and the loop read and write one variable with no ordering between them. Copying the counter into a body local removes the sharing.
- In C#, does copying the counter into a body local cost anything compared with the buggy version?Yes, a little. The buggy loop allocates one closure object for `i` before the loop; the fixed loop allocates a closure object per iteration for `index`, plus a delegate per iteration in both versions. For a handful of buttons that is irrelevant, and correctness wins.
- Expects the for-loop callbacks to print 0, 1, 2 because each lambda copies i.
- Predicts 2 as the printed value instead of the final counter value 3.
- Says foreach still shares one iteration variable in current C#.
- Proposes marking the lambda static to stop it from sharing the counter.
- Thinks moving the declaration of i outside the for statement fixes it.