C# ยท Chapter 17 of 46

C# Switch

The switch statement is an alternative to long if/else if chains when comparing one variable against many possible values. Each case represents a possible match, and break stops execution from falling into the next case.

Modern C# also supports switch expressions, a more concise syntax that directly returns a value based on the matched case.

Syntax
switch (value) {
  case 1:
    // code
    break;
  default:
    // code
    break;
}

switch statement

A switch statement compares a value against several case labels. When a match is found, the corresponding code runs, and break exits the switch. default handles any unmatched value.

switch expressions

Switch expressions use `=>` to map cases directly to values, avoiding repetitive break statements and making pattern matching more concise.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int day = 3;
    switch (day) {
      case 1:
        Console.WriteLine("Monday");
        break;
      case 3:
        Console.WriteLine("Wednesday");
        break;
      default:
        Console.WriteLine("Other day");
        break;
    }
  }
}
Output
Wednesday

day matches case 3, so 'Wednesday' is printed and break exits the switch.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    int day = 6;
    string name = day switch {
      1 => "Monday",
      6 => "Saturday",
      _ => "Unknown"
    };
    Console.WriteLine(name);
  }
}
Output
Saturday

The switch expression maps day 6 directly to the string 'Saturday'.

Key points

  • switch compares one value against multiple case labels.
  • break prevents execution from falling into the next case.
  • default handles any value that doesn't match a case.
  • Switch expressions (=>) offer a more concise alternative syntax.
๐Ÿ’ก Note: Forgetting break in a traditional switch statement (in some languages) causes fall-through, but C# requires an explicit jump statement in each non-empty case.

๐Ÿ“ Quick Quiz

1. What does break do inside a switch case?

2. What does default handle in a switch?

3. What symbol is used in a switch expression to map a case to a value?