Skip to content
Tutorials Center
My learning

Topics

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.

C#
while (queue.Count > 0)
{
    Process(queue.Dequeue());
}

do
{
    attempt++;
} while (!TryConnect() && attempt < 3);

Try it

C# while versus do-while

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.

C# Reading lines until the input ends

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

C#
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

  • continue in a while jumps 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 null is 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 for when you have a counter, foreach for collections and while for everything condition-driven.
  • Performance: all loop forms compile to the same kind of branch; no form is faster in itself.