Skip to content

Choosing with switch

The Course
•
25 min study

An if chain runs blocks of statements. Often, though, all you want is to choose a value. C# has two compact tools for that: the conditional operator for two options, and the switch expression for several.

The conditional operator

condition ? a : b gives a when the condition is true and b otherwise. Because it produces a value, you can use it directly in an assignment or inside an interpolated string. Keep it to simple choices; nesting several of them gets hard to read.

Two options, one value C#
bool done = false;
int minutes = 25;

string state = done ? "Done" : "Todo";
Console.WriteLine($"{state}: {minutes} min");
Console.WriteLine(done ? 0 : minutes);
Check your prediction
Text
Todo: 25 min
25

The switch expression

A switch expression compares one value against a list of patterns, top to bottom, and produces the result of the first arm that matches. Each arm is pattern => result. The arms are separated by commas, and the whole thing ends with a semicolon because it's part of a statement. _ means "anything else".

Match a value C#
int day = 2;

string title = day switch
{
    1 => "Your First Programs",
    2 => "Decisions and Repetition",
    3 => "Methods and Checks",
    _ => "Later in the course",
};

Console.WriteLine(title);
Check your prediction
Text
Decisions and Repetition

Patterns can do more than match one exact value. < 30 matches a range, and and, or and not combine patterns. Because arms are tried in order, each arm below only has to describe its upper limit.

Ranges as patterns C#
int minutes = 45;

string size = minutes switch
{
    < 1 or > 180 => "Invalid",
    < 30 => "Short",
    < 60 => "Medium",
    _ => "Long",
};

Console.WriteLine($"{minutes} minutes: {size}");
Check your prediction
Text
45 minutes: Medium

Test 0, 29, 30, 59, 60 and 181. Compare that with the if chain you would need for the same rules; every case is now on one line and the chain's structure is out of the way.

The compiler watches your cases

A switch expression must produce a value for every input, so the compiler warns you if you leave a gap, and it's an error if an arm can never be reached. If you ignore that warning and a value really does fall through, the program crashes while running. Here the last arm is missing, and 3 has nowhere to go.

A missing case C#
int day = 3;

string title = day switch
{
    1 => "One",
    2 => "Two",
};

Console.WriteLine(title);
Check your prediction
Text
warning CS8509
Unhandled exception. System.Runtime.CompilerServices.SwitchExpressionException

Read warnings as carefully as errors. The program still ran, but the compiler told you about this exact crash before it happened. Add a _ arm to fix it.

Your turn

Exercise

Name the study level

Given a completed number of lessons out of 30, choose a label with a switch expression. Below 0 or above 30 is Invalid. 0 is Not started. 1 to 9 is Beginning, 10 to 29 is Underway, and 30 is Finished. Print Lessons: 12 - Underway for the value 12, then test 0, 9, 10, 29, 30, -1 and 31.

Your workspace C#
int completed = 12;
Console.WriteLine(completed);
Hint 1: the idea

Put the invalid values first, then the exact values, then the ranges. Each arm can assume the earlier ones didn't match.

Hint 2: a first step

Start with an arm for < 0 or > 30 and a final _ arm, and check an invalid value before you fill in the middle.

Show one solution
C#
int completed = 12;

string label = completed switch
{
    < 0 or > 30 => "Invalid",
    0 => "Not started",
    < 10 => "Beginning",
    < 30 => "Underway",
    _ => "Finished",
};

Console.WriteLine($"Lessons: {completed} - {label}");
Text
Lessons: 12 - Underway

The arms are tried from the top, so the invalid range comes first and 0 comes before < 10; otherwise 0 would be called "Beginning". The final _ arm catches everything left, which here is exactly 30.

Move the < 10 arm above the 0 arm and read what the compiler says. Why can the 0 arm never be reached now?

Was this article helpful?

Your response is saved on this device.