SyntaxStudy
Sign Up
C# Loops and Iteration
C# Beginner 1 min read

Loops and Iteration

The `foreach` loop is the idiomatic way to iterate over any type that implements `IEnumerable`, including arrays, lists, dictionaries, and LINQ queries. For index-based access use `for`; for unknown iteration counts use `while` or `do/while`. `break` exits the innermost loop immediately; `continue` skips to the next iteration. Labeled breaks for exiting nested loops are not available in C# — instead, use a boolean flag, a local function with `return`, or refactor into a separate method. C# 8 introduced asynchronous streams with `IAsyncEnumerable`, enabling `await foreach` loops that iterate over data produced asynchronously — for example, streaming rows from a database or pages from a paginated API without loading everything into memory at once.
Example
// Demonstrating for, foreach, while, and do-while loops

// for loop with index
int[] primes = { 2, 3, 5, 7, 11 };
for (int i = 0; i < primes.Length; i++)
    Console.WriteLine($"primes[{i}] = {primes[i]}");

// foreach — cleaner, no index needed
foreach (int p in primes)
    Console.Write($"{p} ");
Console.WriteLine();

// foreach over a dictionary
var capitals = new Dictionary<string, string>
{
    ["France"] = "Paris",
    ["Germany"] = "Berlin",
    ["Japan"] = "Tokyo"
};
foreach (var (country, capital) in capitals)
    Console.WriteLine($"{country} => {capital}");

// while loop
int countdown = 5;
while (countdown > 0)
{
    Console.Write($"{countdown} ");
    countdown--;
}
Console.WriteLine("Go!");

// do-while — body runs at least once
int roll;
var rng = new Random();
do
{
    roll = rng.Next(1, 7);
    Console.WriteLine($"Rolled: {roll}");
} while (roll != 6);

// break and continue
for (int n = 0; n < 10; n++)
{
    if (n % 2 == 0) continue;  // skip evens
    if (n == 7)     break;     // stop at 7
    Console.Write($"{n} ");    // prints: 1 3 5
}