switch statements and expressions
Choose between many options cleanly with switch statements and modern switch expressions.
9 min read
You will learn
- Write a switch statement with case and default
- Group several cases together
- Use switch expressions to compute a value
- Use relational patterns like `>= 90` inside a switch
When if/else gets long
Picking an action based on one value with if/else if gets repetitive:
if (command == "start") Start();
else if (command == "stop") Stop();
else if (command == "pause") Pause();
else Console.WriteLine("Unknown command");A switch says the same thing more clearly: look at this one value, and pick a branch.
The switch statement
switch (command)
{
case "start":
Start();
break;
case "stop":
Stop();
break;
case "pause":
case "hold": // several cases can share one block
Pause();
break;
default: // nothing else matched
Console.WriteLine("Unknown command");
break;
}Each section must end with break (or return, throw…). C# doesn't allow one case to "fall through" into the next by accident — a famous source of bugs in C and JavaScript.
Switch expressions: switch that produces a value
Very often you use a switch just to compute a value. Switch expressions do that with much less ceremony:
string emoji = weather switch
{
"sunny" => "☀️",
"rainy" => "🌧️",
"snowy" => "❄️",
_ => "🤷", // the discard pattern: anything else
};- The value comes before
switch. - Each arm is
pattern => result, separated by commas. _matches anything — likedefault.
Patterns make switches powerful
Arms aren't limited to exact values. You can combine values with or, and compare with relational patterns:
string DayType(string day) => day switch
{
"Saturday" or "Sunday" => "Weekend",
_ => "Weekday",
};
string Grade(int score) => score switch
{
< 0 or > 100 => "Invalid",
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
_ => "F",
};Arms are tested top to bottom, and the first match wins — so >= 80 is only reached for scores below 90.
Tip
The compiler checks your switch expressions: it warns when some inputs aren't handled, and reports an error when an arm can never be reached because an earlier one already covers it.
Switching on characters, numbers and more
Any type with constant values works:
double Apply(double a, char op, double b) => op switch
{
'+' => a + b,
'-' => a - b,
'*' => a * b,
'/' => a / b,
_ => throw new ArgumentException($"Unknown operator {op}"),
};You'll see much richer patterns — matching on types and object properties — in the Modern C# features module.
Try it
C# runtime not loaded
Key takeaways
switchstatements pick a branch based on one value; each section ends withbreak.- Switch expressions (
value switch { ... }) compute a value concisely. _is the catch-all arm;orcombines patterns;<,>=etc. are relational patterns.- Arms are checked in order — the first match wins.
Exercise
DayType returns "Weekend" for "saturday"/"sunday", "Weekday" for the other five days and "Unknown" otherwise — in any letter case. Calculate applies an operator ('+', '-', '*', '/') to two numbers and returns double.NaN for any other operator.
C# runtime not loaded
Hint 1
Normalize the input first with day.ToLower(), then switch on the result.
Hint 2
Several values can share an arm: "saturday" or "sunday" => "Weekend".
Hint 3
A switch expression with a discard arm works nicely for Calculate: op switch { '+' => a + b, ..., _ => double.NaN }.
Show solution
string DayType(string day) => day.ToLower() switch
{
"saturday" or "sunday" => "Weekend",
"monday" or "tuesday" or "wednesday" or "thursday" or "friday" => "Weekday",
_ => "Unknown",
};
double Calculate(double a, char op, double b) => op switch
{
'+' => a + b,
'-' => a - b,
'*' => a * b,
'/' => a / b,
_ => double.NaN,
};
Console.WriteLine(DayType("Saturday"));
Console.WriteLine(Calculate(6, '*', 7));Quiz
4 questions · 3 correct to pass1.In a switch statement, what does `default:` do?
2.What does C# require at the end of each non-empty case section in a switch statement?
3.What does `_ =>` mean in a switch expression?
4.What does `score switch { >= 90 => "A", >= 80 => "B", _ => "C" }` return for 85?
To complete this lesson
- ○ Solve the exercise
- ○ Pass the quiz (3/4 correct)