Loops in C#
The four loop constructs C# offers, and when to reach for each one.
2 min read
C# gives you four ways to repeat code, and each communicates a slightly different intent to whoever reads it later.
for: when you know the count
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}The three parts — initializer, condition, increment — run in that order every iteration. Use for when the loop is fundamentally about a counter or index.
while and do-while: when you don't know the count upfront
int attempts = 0;
while (attempts < 3)
{
Console.WriteLine("Attempt " + attempts);
attempts++;
}while checks the condition before each iteration, so it might not run at all. do-while checks after, guaranteeing at least one run:
string? input;
do
{
Console.Write("Enter 'quit' to exit: ");
input = Console.ReadLine();
} while (input != "quit");That's the right shape whenever "run once, then keep going while a condition holds" describes what you actually want — a menu prompt being the classic example.
foreach: when you're iterating a collection
var names = new List<string> { "Ada", "Grace", "Alan" };
foreach (var name in names)
{
Console.WriteLine(name);
}foreach is the most common loop in real C# code. It works over anything implementing IEnumerable<T> (arrays, lists, dictionaries, and — as you'll see in the LINQ lessons — query results), and it reads directly as "for each item in this collection," with no index bookkeeping to get wrong.
break and continue
Both work the same as in most C-family languages:
foreach (var name in names)
{
if (name == "Grace") continue; // skip this iteration
if (name == "Alan") break; // stop the loop entirely
Console.WriteLine(name);
}Choosing the right one
Default to foreach whenever you're processing a collection and don't need the index. Reach for for when you genuinely need the index (or need to loop over a range without a backing collection), and while/do-while when the stopping condition isn't "run N times" but "keep going until something happens." Picking the loop that matches your actual intent makes the code more honest about what it's doing, even before anyone reads the body.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.