Skip to main content

Switch Statements

A switch statement checks one value against a list of cases and runs the block for the first case that matches.

When you're comparing a single variable against many constants, it often reads more clearly than a long if/else if chain.

switch (expression)
{
case valueA:
// code block
break;
case valueB:
// code block
break;
default: // runs if nothing else matches (optional)
// code block
break;
}

Each case label must be unique. Every non-empty section must end with a jump statement like break or return (like what we do inside loops).

Common errors​

C# doesn't allow implicit fall-through. A missing break causes errors, for example:

string color = "red";
switch (color)
{
case "blue":
Console.WriteLine("Blue");
break;
case "red":
Console.WriteLine("Red");
// ❌ Error missing break
default:
Console.WriteLine("Unknown");
break;
}