Say you’re closing out the register at a Denver bike shop, and the cashier typed an unknown number of sales before typing done.
You can’t know the count up front, and that’s exactly the job of a while loop in C#: it repeats a block for as long as a condition stays true.
In this tutorial, I’ll total that register with the while loop in C# on .NET 10. You’ll write a counter loop, read input until a sentinel, validate input, use break and continue, and fix the mistakes behind most infinite loops.
The Sample Data for Our while Loop Examples
Every example works on the same seven lines a cashier typed, in this order:
| # | Entry | Why it’s there |
|---|---|---|
| 1 | 125.50 | Valid sale |
| 2 | 89.99 | Valid sale |
| 3 | abc | Typo, not a number |
| 4 | -20 | Negative, not a sale |
| 5 | 310.00 | Valid sale |
| 6 | done | Sentinel: stop reading |
| 7 | 45.00 | Typed after done, must be ignored |
A good loop skips rows 3 and 4, never reads row 7, and totals the valid sales to $525.49.
While Loop Syntax in C#
The syntax has just a keyword, a Boolean condition in parentheses and a body:
while (condition)
{
// runs again and again while condition is true
}
C# checks the condition before each pass. If it’s false the first time, the body never runs, so a while loop runs zero or more times. That’s the key difference from a do-while loop in C#, which always runs at least once.
You’ll need the .NET 10 SDK to follow along. I run these as single-file apps with dotnet run File.cs in VS Code; see how to create a console application in Visual Studio Code if that’s new.
Method 1: Counter-Controlled while Loop (Recommended Start)
Use a counter when you know where the loop should stop, like the end of an array. Same input array, now printed with their position:
string[] entries =
["125.50", "89.99", "abc", "-20", "310.00", "done", "45.00"];
int i = 0; // 1. start the counter
while (i < entries.Length) // 2. check before every pass
{
Console.WriteLine($"Entry {i + 1}: {entries[i]}");
i++; // 3. move toward the exit
}
Console.WriteLine($"Loop ended with i = {i}");
Output:
Entry 1: 125.50
Entry 2: 89.99
Entry 3: abc
Entry 4: -20
Entry 5: 310.00
Entry 6: done
Entry 7: 45.00
Loop ended with i = 7

All seven entries print, and the last line is Loop ended with i = 7.
How does this code work?
Three parts make a counter loop work. int i = 0 creates the variable before the loop, i < entries.Length is checked before every pass, and i++ moves the counter toward the exit.
When i hits 7, the condition is false and C# jumps to the line after the loop. Arrays are zero-based, so entries[i] reads index 0 through 6; my C# array guide covers that in detail.
Method 2: Read Input Until a Sentinel with a while Loop
This is where while loops shine: you don’t know how many lines are coming, only the value that ends them. Same register input, now arriving one line at a time from a TextReader:
TextReader input = new StringReader(
"125.50\n89.99\nabc\n-20\n310.00\ndone\n45.00"); // or Console.In
int count = 0;
string? line = input.ReadLine();
while (line is not null && line != "done")
{
count++;
Console.WriteLine($"Read: {line}");
line = input.ReadLine();
}
Console.WriteLine($"{count} entries before \"done\"");
Output:
Read: 125.50
Read: 89.99
Read: abc
Read: -20
Read: 310.00
5 entries before "done"
It reads five lines, prints 5 entries before "done", and never touches 45.00.
How does this code work?
StringReader stands in for the keyboard so every run is the same. Swap it for Console.In and the same loop reads what a user types, because both are a TextReader.
The first ReadLine() happens before the loop and the next one at the bottom of the body. line is not null guards against the input running out, which ReadLine() signals with null (more in checking for null values in C#).
Method 3: while Loop with break and continue
Now let’s total the sales. Same register input, but the bad rows have to be skipped instead of printed:
using System.Globalization;
CultureInfo.CurrentCulture = new("en-US");
TextReader input = new StringReader(
"125.50\n89.99\nabc\n-20\n310.00\ndone\n45.00");
decimal total = 0;
string? line;
while ((line = input.ReadLine()) is not null)
{
if (line == "done") break; // stop at the sentinel
bool ok = decimal.TryParse(line, out decimal amount);
if (!ok || amount <= 0)
{
Console.WriteLine($"Skipped \"{line}\"");
continue; // bad entry: next line
}
total += amount;
}
Console.WriteLine($"Total sales: {total:C}");
Output:
Skipped "abc"
Skipped "-20"
Total sales: $525.49

It skips abc and -20, then prints Total sales: $525.49.
How does this code work?
while ((line = input.ReadLine()) is not null) reads and tests in one step, so there’s no second ReadLine() at the bottom. That’s the common shape for reading files and streams.
break leaves the loop the moment it sees done. continue jumps straight back to the condition, skipping total += amount. decimal.TryParse returns false for abc instead of throwing, the same idea as when you convert a string to double in C#.
Note: the file sets the culture to en-US, because TryParse and :C follow the machine’s region.
Method 4: Validate Input with a while Loop
Sometimes you need one good value, and you want to ask again until you get it. Same idea, with the first three things the cashier tried for a price:
using System.Globalization;
CultureInfo.CurrentCulture = new("en-US");
TextReader input = new StringReader("abc\n-20\n125.50");
string? text = Ask();
decimal price;
while (!decimal.TryParse(text, out price) || price <= 0)
{
Console.WriteLine($" Not a valid price: {text}");
text = Ask();
}
Console.WriteLine($"Saved {price:C}");
string? Ask()
{
Console.Write("Price: ");
string? t = input.ReadLine();
Console.WriteLine(t); // echo the typing
return t;
}
Output:
Price: abc
Not a valid price: abc
Price: -20
Not a valid price: -20
Price: 125.50
Saved $125.50

It rejects abc and -20, then prints Saved $125.50.
How does this code work?
The condition is the validation rule: keep looping while TryParse fails or the price isn’t positive. The || short-circuits, so price <= 0 is only checked after a successful parse.
If the first entry is valid, the body never runs, so the error only shows when there’s an error. Prices with thousands separators need one more step; see converting a number with commas to decimal.
Method 5: Infinite Loop with while (true) and break
while (true) runs forever unless something inside stops it. It’s the cleanest choice when a loop has more than one exit. Same register input again, but now we stop either at done or as soon as we hit a $400 daily goal:
using System.Globalization;
CultureInfo.CurrentCulture = new("en-US");
TextReader input = new StringReader(
"125.50\n89.99\nabc\n-20\n310.00\ndone\n45.00");
decimal total = 0, goal = 400m;
while (true)
{
string? line = input.ReadLine();
if (line is null || line == "done") break; // exit 1
bool ok = decimal.TryParse(line, out decimal amount);
if (!ok || amount <= 0) continue; // skip
total += amount;
Console.WriteLine($"+{amount:C} = {total:C}");
if (total >= goal) break; // exit 2
}
Console.WriteLine($"Stopped at {total:C}, goal {goal:C}");
Output:
+$125.50 = $125.50
+$89.99 = $215.49
+$310.00 = $525.49
Stopped at $525.49, goal $400.00

Three sales print, ending at +$310.00 = $525.49, then Stopped at $525.49, goal $400.00.
How does this code work?
Each exit is an explicit break. The goal check fires after 310.00, so the loop never reaches done here.
for ( ; ; ) does the same job, but while (true) reads better. For menus, put a switch case in C# inside the loop and break out on Quit.
Pro Tip: make sure every path through a while (true) body can reach a break, return or throw.
While vs do-while vs for Loop in C#: What’s the Difference?
Here are all three on the same starting point, an empty stock count:
int stock = 0;
while (stock > 0)
Console.WriteLine("while: never printed");
do
Console.WriteLine("do-while: printed once");
while (stock > 0);
for (int day = 1; day <= 3; day++)
Console.Write($"day {day} ");
Console.WriteLine("<- for");
Output:
do-while: printed once
day 1 day 2 day 3 <- for
The while loop prints nothing, because stock > 0 is false on the first check. The do-while prints once before it checks. The for loop counts days 1 to 3.
| while | do-while | for | |
|---|---|---|---|
| Condition checked | Before each pass | After each pass | Before each pass |
| Minimum runs | 0 | 1 | 0 |
| Best for | Unknown count, sentinel, input | Menus, run-at-least-once | Known count, index |
| Counter scope | Outside the loop | Outside the loop | Inside the loop |
When I need the index and know the count, I write a for loop in C#. To read every item of a collection, a foreach loop is shorter and can’t go out of range.
Common while Loop Mistakes (and How to Fix Them)
Off-by-One: <= Instead of <
Same input array, cut to three. One extra = reads one item past the end:
string[] entries = ["125.50", "89.99", "abc"];
int i = 0;
while (i <= entries.Length) // bug: should be <
{
Console.WriteLine(entries[i]);
i++;
}
Output (unhandled exception):
125.50
89.99
abc
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<Main>$(String[] args) in C:\DotNetDemo\WhileLoopDemo\OffByOne.cs:line 6

The three entries print, then IndexOutOfRangeException. Use i < entries.Length; the last valid index is always Length - 1.
Forgetting the Increment
Drop the i++ and the condition never changes, so this prints 125.50 until you press Ctrl+C:
int i = 0;
while (i < entries.Length)
Console.WriteLine(entries[i]); // no i++: runs forever
Which while Loop Pattern Should You Use?
| Situation | Pattern |
|---|---|
| Known end, like an array length | Method 1: counter loop (or a for loop) |
| Read until a stop value or end of input | Method 2: sentinel loop |
| Skip bad rows, stop early | Method 3: continue and break |
| Need one valid value from the user | Method 4: re-prompt loop |
| Several ways to finish | Method 5: while (true) with break |
Things to Keep in Mind
- The condition is checked first. A false condition means zero runs; use do-while when you need one.
- Something must change. Every pass should move the counter, read input or flip a flag.
- break only exits the innermost loop. In nested loops, use a flag or move the loops into a method and
return. - Watch
<=with arrays. The last index isLength - 1. - Set the culture when parsing money.
TryParseand:Cfollow the machine’s region.
Want more practice with loops? These programs all use one:
- Print the factorial of a number in C#
- Check whether a number is prime in C#
- Reverse a string in C# with and without a loop
- Generate random numbers in C# without repeats
Frequently Asked Questions
What is a while loop in C#?
It’s an iteration statement that runs its body as long as a Boolean condition is true. The condition is checked before each pass, so the body can run zero times.
What is the difference between while and do-while in C#?
A while loop checks its condition before the body and runs zero or more times. A do-while checks after the body and runs one or more times, as the iteration statements reference on Microsoft Learn explains.
How do I stop an infinite while loop in C#?
Inside the code, use break, return or throw on a condition that will eventually be met. In a running console app, press Ctrl+C to end the process.
Does break exit all nested while loops?
No. break ends only the innermost loop that contains it. To leave outer loops, set a flag that their conditions check, or put the loops in a method and use return.
Can a while loop read user input until the user types a word?
Yes. Read with Console.ReadLine() and loop while the line isn’t null and isn’t your stop word, such as done. Reading a TextReader lets you test the same loop with a StringReader.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…