C# Switch

When you need to compare one value against many possible options, a long chain of else if statements can get hard to read. The switch statement lets you pick a block of code to run based on a single value in a cleaner, more organized way.

The switch Statement

A switch statement takes one expression and compares it against a list of case labels. When it finds a match, it runs the code for that case. This is ideal for menu choices, day names, status codes, and similar situations with a fixed set of values.

Switching on a day number

int day = 4;

switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 4:
        Console.WriteLine("Thursday");
        break;
    default:
        Console.WriteLine("Another day");
        break;
}
// Output: Thursday

The break and default Keywords

The break keyword tells C# to stop and jump out of the switch once a matching case has run. The default label is optional and works like else, running when no case matches the value.

  • Each case label ends with a colon (:).
  • Every case that contains code must end with break (or return).
  • The default case handles any value not covered by the other cases.
  • You can list multiple case labels together to share the same block.
Note: Unlike some languages, C# does not allow accidental fall-through between cases that contain code. If you forget break, the compiler reports an error, which helps you catch mistakes early.

Grouping Cases

You can stack several case labels so they run the same code. This is handy when different values should be treated the same way, such as grouping weekend days together.

Weekday or weekend

int day = 6;

switch (day)
{
    case 6:
    case 7:
        Console.WriteLine("Weekend");
        break;
    default:
        Console.WriteLine("Weekday");
        break;
}
// Output: Weekend
PartPurpose
switch (value)The expression being tested.
case x:A block that runs when value equals x.
break;Exits the switch after a case runs.
default:Runs when no case matches.

A switch is often easier to read than a long if...else chain when you are testing the same variable against many constant values. If your conditions involve ranges or complex comparisons, an if...else chain may still be the better choice.

Exercise: C# Switch

In C#, what happens after a matching case block finishes executing without a break or other jump statement?