C#
The switch statement
Learn multi-way selection with switch, case, break and default.
The switch statement
To select among many branches based on a single value you use switch. switch (day) takes the value and each case label compares it to a possible value. You exit the branch with break.
If no case matches, the default branch runs. switch reads better than a long else if chain, especially when selecting on enum or integer values.
break and fall-through
C# has no automatic fall-through between case branches; each branch must end with break (or return, goto). This prevents accidental fall-through bugs.
To send multiple values to the same block you can stack case labels: case 1:\ncase 2: Console.WriteLine("small"); break;. Here 1 and 2 produce the same output; this only works for a shared block.
Exercise Turn a day number into a name
Declare a day variable with the value 3. Use switch on day: case 1 prints "monday", case 2 "tuesday", case 3 "wednesday", and default prints "unknown". Use break in each case.
Show example solution
Open switch (day), write case 1/2/3 and default branches each ending with break.
Example solution:
using System;
class Program
{
static void Main()
{
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("monday");
break;
case 2:
Console.WriteLine("tuesday");
break;
case 3:
Console.WriteLine("wednesday");
break;
default:
Console.WriteLine("unknown");
break;
}
}
}
Test yourself
-
Match each switch part to its meaning
- switch
- Takes the value
- case
- A possible value
- break
- Exits the branch
- default
- When none match
-
What does 'case 1: case 2: Console.WriteLine("x"); break;' do in a switch?
switch (n) {
case 1:
case 2:
Console.WriteLine("x");
break;
}
- Prints 'x' only for n=1
- Prints 'x' for both n=1 and n=2
- Raises a compile error
- Prints nothing
Show answer
Prints 'x' for both n=1 and n=2 — Correct. Empty case labels stacked together share the same block.
-
Start the default branch
switch (code)
{
case 1:
Console.WriteLine("one");
break;
____:
Console.WriteLine("unknown");
break;
}
Show answer
switch (code)
{
case 1:
Console.WriteLine("one");
break;
default:
Console.WriteLine("unknown");
break;
}
Next lesson: Pattern matching