A C# do while loop runs its body first and checks the condition afterwards, so the body always executes at least once: do { ... } while (condition);. Use it when you need one pass before you can decide whether to repeat, such as reading input and then validating it.
int n = 0;
do
{
Console.Write(n);
n++;
} while (n < 5);
// Output: 01234
That is the example from Microsoft's iteration statements reference. It prints 01234 on one line.
C# do while syntax
The form is the keyword do, a statement or a block, the keyword while, a Boolean expression in parentheses, and a semicolon:
do
{
// body: runs at least once
} while (condition);
The C# language specification defines it as do embedded_statement while ( boolean_expression ) ;. Three details follow from that definition.
- The semicolon is required. A
whileloop has no semicolon after its condition, and ado whileloop does. This is the most common typo when switching between the two. - The condition must be a Boolean expression. As in the other C# loops, an
intsuch as1is not treated as true. - The body can be a single statement, but use braces. Without braces the code compiles only for one statement, and a second line added later silently falls outside the loop.
Per the specification, when control reaches the end of the body, the condition is evaluated. If it is true, control returns to the start of the loop. Otherwise the loop ends and execution continues with the next statement.
Do while vs while in C#
The only difference is when the condition is tested. Microsoft's documentation says the do statement evaluates the expression after each execution, so it runs one or more times, while the while statement evaluates it before each execution, so it runs zero or more times. Here is the same loop written both ways with a condition that is false from the start:
int count = 10;
while (count < 5)
{
Console.WriteLine("while body");
}
do
{
Console.WriteLine("do body");
} while (count < 5);
Example output: only do body, once. The while loop never enters its body because 10 < 5 is false on the first check. The do loop has already run its body before it gets to the same check.
while | do while | |
|---|---|---|
| Condition checked | before each pass | after each pass |
| Minimum passes | 0 | 1 |
| Semicolon after condition | no | yes |
| Best for | "repeat while something holds" | "do it once, then ask whether to repeat" |
Example: ask until the input is valid
This is the classic use. You cannot validate input you have not read yet, so the read has to happen inside the loop, and a plain while would force you to read once before the loop and again at the bottom of it.
int age;
bool isValid;
do
{
Console.Write("Enter your age (0-120): ");
string? text = Console.ReadLine();
isValid = int.TryParse(text, out age) && age is >= 0 and <= 120;
if (!isValid)
{
Console.WriteLine("That is not a valid age. Try again.");
}
} while (!isValid);
Console.WriteLine($"Age recorded: {age}");
Example session:
Enter your age (0-120): abc
That is not a valid age. Try again.
Enter your age (0-120): 200
That is not a valid age. Try again.
Enter your age (0-120): 34
Age recorded: 34
Notice that age and isValid are declared before the do keyword. The specification says the scope of a local variable declared in a block is that block, and the while (...) condition is outside the braces. Declaring isValid inside the body and testing it in the condition is a compile error, because the name is not in scope there.
One practical caution: Console.ReadLine() returns null when the input stream has ended, for example when input is redirected from an empty file. In that case this loop would prompt forever, so add an exit path (a break when text is null) in anything that can run without a person at the keyboard.
Example: a menu that repeats until the user quits
A menu must be shown at least once, which suits do while:
string? choice;
do
{
Console.WriteLine("1) Say hello");
Console.WriteLine("2) Say goodbye");
Console.WriteLine("q) Quit");
choice = Console.ReadLine();
switch (choice)
{
case "1":
Console.WriteLine("Hello");
break;
case "2":
Console.WriteLine("Goodbye");
break;
}
} while (choice != "q");
The break statements here end the switch sections only. Microsoft's jump statements reference points this out: a break at the end of a switch section transfers control out of the switch and leaves the enclosing loop alone. The loop ends only when the condition choice != "q" becomes false.
Example: retry an operation a limited number of times
Retry logic has the same shape: attempt once, then decide whether to try again. Put a hard cap in the condition so a permanent failure cannot loop forever.
const int maxAttempts = 3;
int attempt = 0;
bool succeeded = false;
do
{
attempt++;
succeeded = TryConnect(); // your own method returning bool
if (!succeeded)
{
Console.WriteLine($"Attempt {attempt} of {maxAttempts} failed.");
}
} while (!succeeded && attempt < maxAttempts);
If TryConnect() fails every time, the loop runs exactly 3 times and stops. If the first call succeeds, it runs once. In real code you would usually add a delay between attempts, but that is outside the loop mechanics shown here.
break and continue in a do while loop
Both statements work as in the other loops. The jump statements reference says break terminates the closest enclosing iteration statement (for, foreach, while or do), and continue starts a new iteration of it. The specification adds the detail that matters for do while: continue transfers control to the end of the body, and from there the condition is evaluated.
int i = 0;
do
{
i++;
if (i % 2 == 0) continue; // jumps to the condition check
if (i > 7) break; // leaves the loop
Console.WriteLine(i);
} while (i < 10);
Example output: 1, 3, 5, 7, one per line. At i == 9 the break fires and the loop ends before i reaches 10.
The counter update comes before the continue on purpose. If you wrote i++ at the bottom of the body and used continue earlier, the skipped update would leave i unchanged, the condition would stay true and the loop would never end. A for loop avoids this because its iterator section runs even after continue, and a do while loop has no such section. For nested loops, break leaves only the innermost loop. The reference lists goto, a method with return, and (starting in C# 15) a labeled break as ways out of several levels at once.
Infinite do while loops
A condition that is always true makes a loop that only break, return or an exception can leave:
do
{
string? line = Console.ReadLine();
if (line is null or "exit") break;
Console.WriteLine($"You typed: {line}");
} while (true);
The specification notes that the end point of a do statement is reachable if it contains a reachable break or if the condition is not the constant true. In practice, the compiler understands that code after a do { } while (true); with no break can never run. Accidental infinite loops are more often a condition that never changes, such as testing a variable that the body forgets to update.
When to use do while instead of for or while
- Use
do whilewhen the body has to run once before the condition can be evaluated: prompts, menus, retries, reading a first value. - Use
whilewhen the work might not be needed at all, for example processing a queue that could be empty. - Use
forwhen you are counting or stepping through indexes. See C# for loop: syntax, examples, foreach and break/continue for those. - Use
foreachwhen you only need each element of a collection.
In practice do while is the least used of the four. If you find yourself writing a pre-loop read and repeating it at the bottom of a while body, that duplication is the signal to switch to do while. If a loop could be written either way and zero passes is a valid outcome, prefer while.
Common mistakes
- Missing semicolon after the condition. The compiler rejects
} while (x < 5)with nothing after it. - Declaring the tested variable inside the body. It is out of scope in the condition. Declare it above the
do. - Forgetting that the first pass is unconditional. If running the body with bad data is harmful, for example dividing by a value that may be zero, validate before the loop or use
while. - Never changing the tested value. If nothing in the body can make the condition false, add an exit path or a counter cap.
Frequently asked questions
- What is the difference between while and do while in C#?
- A while loop tests its condition before each pass, so the body can run zero times. A do while loop tests the condition after each pass, so the body always runs at least once. Microsoft's reference describes it the same way: do executes one or more times, while executes zero or more times.
- Does a C# do while loop need a semicolon?
- Yes. The C# language specification defines the statement as do, an embedded statement, while, a Boolean expression in parentheses, and a closing semicolon. Leaving the semicolon after the closing parenthesis out is a compile error.
- Can I use a variable declared inside a do while body in the condition?
- No. A variable declared inside the braces is scoped to that block, and the while condition sits outside it. Declare the variable before the do keyword if the condition needs it.
- What does continue do in a do while loop?
- It jumps to the end of the loop body, which means the condition is evaluated next. If the condition is still true, another iteration starts. This is why a continue placed before the counter update can cause an endless loop.