Conditions and loops

C# · Essentials · 10 min

Every algorithm is built from choosing between paths and repeating steps.

if / else if / else takes a bool condition; C# does not treat numbers or null as true/false, so if (count) does not compile. Combine conditions with &&, || and !, which short-circuit. The conditional operator cond ? a : b picks a value.

A switch statement compares one value against cases. Each section must end with break, return or throw; there is no fall-through between non-empty sections. Cases can be constants or patterns (case > 100:).

Loops:

  • for (int i = 0; i < n; i++) when you need the index.
  • foreach (var item in items) to walk any collection; you cannot reassign item and must not add or remove items from a List while iterating it.
  • while (cond) checks first; do { } while (cond); runs at least once.

break leaves the innermost loop, continue skips to the next iteration. To leave nested loops, move them into a method and return.

For many value-to-result mappings, the switch expression (x switch { 1 => "one", _ => "many" }) is usually clearer than a switch statement; it is covered in the pattern matching lesson.

Ranges of numbers are produced with for or Enumerable.Range(start, count), which works nicely with foreach.

Example

int[] scores = [72, 95, 40, 88];

foreach (var s in scores)
{
    string grade;
    if (s >= 90) grade = "A";
    else if (s >= 70) grade = "B";
    else grade = "F";
    Console.Write($"{s}:{grade} ");     // 72:B 95:A 40:F 88:B
}
Console.WriteLine();

for (int i = 0; i < scores.Length; i++)
{
    if (scores[i] < 50) continue;
    if (scores[i] > 90) break;
    Console.Write(i + " ");             // 0
}

switch (DateTime.Now.DayOfWeek)
{
    case DayOfWeek.Saturday:
    case DayOfWeek.Sunday: Console.WriteLine("\nweekend"); break;
    default: Console.WriteLine("\nweekday"); break;
}

Remember

  • Conditions must be bool: no truthy numbers or null
  • foreach walks any collection; for when you need the index
  • switch sections cannot fall through; end each with break or return

Watch out for

  • Modifying a List inside a foreach over it, which throws InvalidOperationException.

Check yourself

  1. Which statement about switch statements in C# is true?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements