C# Reference ยท Keywords and Statements
The while and do statements
Reference for C# while and do-while: loop until a condition fails, run the body at least once, read input, avoid infinite loops and use break and continue.
while repeats its body as long as a condition is true, checking the condition before every iteration, so the body may run zero times. do ... while checks the condition after the body, so the body always runs at least once. Use them when you do not know in advance how many repetitions you need: reading until end of input, retrying, polling, or converging on a value.
Both conditions must be bool expressions. A loop whose condition never becomes false runs forever unless the body uses break, return, throw or goto.
while (queue.Count > 0) { Process(queue.Dequeue()); } do { attempt++; } while (!TryConnect() && attempt < 3);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
while (condition) statement do statement while (condition);
| Name | Description |
|---|---|
condition |
A bool expression. In while it is evaluated before each iteration; in do after each iteration. |
statement |
The body: a single statement or a block. |
Errors: a missing semicolon after do ... while (condition) is a syntax error. A stray semicolon after while (condition); silently creates an empty body, so the loop either spins forever or does nothing, and the compiler gives no error.
Usage notes
continuein awhilejumps straight to the condition check, so make sure the code that changes the condition is not skipped, or you create an infinite loop.- Scope in
do: variables declared inside the body are not visible in the condition, so declare them before the loop if the condition needs them. - Assignment in the condition like
(line = ReadLine()) is not nullis common for reading; put it in parentheses and compare explicitly. - Retry loops should be bounded (a counter or a deadline) and usually wait between attempts.
- Long-running loops in async code should check a
CancellationToken:while (!token.IsCancellationRequested). - Choosing: use
forwhen you have a counter,foreachfor collections andwhilefor everything condition-driven. - Performance: all loop forms compile to the same kind of branch; no form is faster in itself.