switch Statement (C#)

A switch statement compares one value against several possible cases and runs the matching block. It is a clean alternative to a long chain of if/else if statements.

C#

Each case ends with break (or return) so execution doesn't fall through to the next case. A default case handles any value that matches none of the others.

Modern C# also offers a switch expression with the => arrow syntax, which returns a value directly and is more concise.

Syntax

switch (value) { case x: ...; break; default: ...; break; }

Examples

C#

int day = 3;
switch (day)
{
    case 1: Console.WriteLine("Mon"); break;
    case 3: Console.WriteLine("Wed"); break;
    default: Console.WriteLine("Other"); break;
}

Output:

Wed

Learn it in a lesson

See also

Back to the Dictionary