skip to content

In C#, how do for, foreach, while and do-while differ in when they test their condition and where their loop variables live?

level: juniorimportance: must knowfreq 70%

answer

  1. zero runs versus at least one
  2. condition checked before or after the body
  3. body block ends before the do condition
  4. foreach variable is read-only

basics

~20 s

for and while test their condition before each pass and may run zero times; do-while tests after the body, so it runs at least once. foreach visits elements through a read-only variable, and loop variables stay inside the loop.

solid answer

~50 s

`while` and `for` evaluate a `bool` condition before every pass, so the body can run zero times; `do { } while (cond);` evaluates it after the body, so the body runs at least once, which suits a sensor read you must attempt before you can judge it. `for` packs an initializer, a condition and an iterator into one header, and a variable declared in that initializer is gone after the loop (CS0103 if you read it later). `foreach` walks a collection; its iteration variable is read-only, so assigning to it is CS1656, though you can still change the members of the object it refers to. One C# trap: a local declared inside a `do` body is out of scope in the `while` condition, so the variable the condition tests must be declared before the `do`.

code

csharp · 23 lines
csharp
int? reading;
int attempt = 0;

do
{
    attempt++;
    reading = ReadGateSensor(attempt);
    Console.WriteLine($"attempt {attempt}: {(reading == null ? "no echo" : reading + " cm")}");
}
while (reading == null && attempt < 3);

string[] lanes = ["entry", "exit"];
foreach (string lane in lanes)
{
    Console.WriteLine($"lane {lane} checked");
}

for (int i = 0; i < lanes.Length; i++)
{
    Console.WriteLine($"lane {i}: {lanes[i]}");
}

static int? ReadGateSensor(int attempt) => attempt < 2 ? null : 140;

go deeper

for a junior

Recall that do-while is the only loop guaranteed to run once, and that for and foreach variables disappear after the loop. Know CS1656 by its meaning: the foreach variable is read-only.

for a middle

Explain the scope rules behind the errors: the do body block closes before the condition, the for initializer is scoped to the statement, and C# conditions must be bool with no int-to-bool conversion.

for a senior

Pick the loop that states intent in review: a bounded retry as do-while or for with break, not while (true) with scattered exits, and explain why foreach cannot write elements back.

for a principal

There is little to decide at lead level here; the value is in review norms, such as preferring bounded loops for retries and index loops only when the index is genuinely needed.

C# has four **iteration statements**: `for`, `foreach`, `while` and `do`. They differ in two ways an interviewer probes: *when* the loop condition is evaluated, and *where* the variables the loop introduces are visible. Both are decided by the compiler, so getting them wrong produces a CS-numbered error rather than a subtle bug. ## When each loop tests its condition | statement | condition tested | minimum passes | natural fit | |---|---|---|---| | `while (cond) body` | before each pass | 0 | repeat while something stays true | | `for (init; cond; iter) body` | before each pass | 0 | a counter or index over a known range | | `do body while (cond);` | after each pass | 1 | act first, then decide whether to repeat | | `foreach (T x in source) body` | before each element | 0 | visit every element of a collection | - The **condition must be a `bool`**. C# has no implicit conversion from `int` to `bool`, so `while (count)` fails with CS0029, "Cannot implicitly convert type 'int' to 'bool'". - Every section of a `for` header is optional; `for (;;)` with no condition loops until a jump statement such as `break` or `return`, or an exception, leaves it. - A `do` statement ends with a semicolon after the `while (...)` clause; it is the only loop whose body always executes at least once. - `foreach` over an empty collection skips the body; `foreach` over a `null` reference throws `NullReferenceException`. ## Where loop variables live The scope rules are what separates someone who has written C# from someone who has read about loops. 1. **A `for` initializer variable** is scoped to the whole `for` statement: the condition, the iterator and the body can use it, the code after the loop cannot. Reading `i` after `for (int i = 0; ...)` is CS0103, "The name 'i' does not exist in the current context". Two loops in a row may each declare their own `i`. 2. **A local declared inside a `do` body** belongs to the body's block, and that block closes before `while (...)` is evaluated. Writing `do { int? reading = Read(); } while (reading == null);` is CS0103 on `reading`. Declare the variable before `do` and assign it inside. 3. **The `foreach` iteration variable** is a read-only local. `lane = lane.Trim();` inside `foreach (string lane in lanes)` is CS1656, "Cannot assign to 'lane' because it is a 'foreach iteration variable'". Mutating the object it refers to (setting a property on a class instance) is allowed; replacing the element needs an index-based loop. ## Choosing a loop: a retry with a fixed budget A parking-garage barrier controller reads an ultrasonic sensor that sometimes returns no echo, and may retry up to three times. Three shapes are correct: - **`do`/`while` with a counter**: read, then test `reading == null && attempt < 3`. The read always happens once, which matches the requirement, and both variables live outside the body so the condition can see them. - **`for` with `break`**: `for (int attempt = 1; attempt <= 3; attempt++) { reading = Read(); if (reading != null) break; }`. The attempt counter stays scoped to the loop; the result variable must be declared before it. - **`while (true)` with `break`**: legal and common, but the exit conditions are scattered through the body; reviewers usually prefer the bounded form. `foreach` is the wrong tool for a retry, because there is no collection to walk; it is the right tool for checking every lane in a `string[]` of lane names, where an index adds nothing. Choose `for` over `foreach` when you need the index itself, need to step by more than one, or need to write elements back. ## What these loops have in common - `break` leaves the nearest enclosing loop (or `switch`), and `continue` jumps to the next evaluation of the nearest loop's condition (for a `for`, after running the iterator section). - `return` leaves the whole method, loop included. - None of the four loops leaks its own variables to the code after it, so a value the loop computes must be held in a variable declared before the loop. ## Neighbouring material How `foreach` finds a `GetEnumerator` method, and why it works on `Span<T>` without any interface, is covered with the enumerator contract. Why lambdas created in a `for` loop all see the final counter while a `foreach` loop gives each its own variable is covered with lambdas and closures. `await foreach` belongs with asynchronous streams.

  • In C#, can a foreach loop change the elements of a List<Ticket> it is iterating?
    It cannot assign the iteration variable (CS1656), so it cannot replace an element. If `Ticket` is a class, setting `ticket.Paid = true` changes the shared object and is fine. Replacing elements needs a `for` loop with the indexer, and even `list[i] = x` inside a `foreach` over that same list throws `InvalidOperationException`, because the indexer's setter counts as modifying the list.
  • In a C# for loop, when does continue run the iterator section?
    `continue` skips the rest of the body and goes to the iterator section, then the condition. So in `for (int i = 0; i < n; i++)` a `continue` still increments `i`. In a `while` loop the increment is part of the body, so a `continue` placed before it skips it and can loop forever, a classic bug when a `for` is rewritten as a `while`.

  • Says a C# while loop always runs its body at least once.
  • Thinks a variable declared inside a do body is visible in its while condition.
  • Believes a for loop counter is still readable after the loop ends.
  • Thinks while (count) works for a nonzero int, as a truthiness test.
  • Believes the foreach iteration variable can be reassigned to replace the element.