Switch Expressions and the Conditional Operator
Choose a value, rather than run a block, with C#'s conditional operator for two choices and a switch expression for many.
Apprentice · C# · Updated
After this lesson you can
- Choose one of two values with the conditional operator ?:
- Turn a value into a result with a switch expression
Key takeaways
- The conditional operator picks one of two values.
isThree ? 3 : 2is 3 whenisThreeistrue, otherwise 2. - A switch expression turns one value into another. Each arm is a pattern,
=>and a result, and the arms are separated by commas. - In a switch expression,
orlets one arm match several values, and_matches anything, so it goes last. - Arms can compare with
<,>,<=and>=and join them withand. C# uses the first arm that matches. - To run different code, use
ifor aswitchstatement; to pick a value, use?:or a switch expression.
Often a decision exists only to pick a value: the price, the label, the message. An if statement or a switch statement can do it, but you have to declare a variable first and set it in every branch. C# has two shorter ways that produce the value directly.
Two choices: the conditional operator
The conditional operator ?: picks one of two values:
// condition ? valueIfTrue : valueIfFalse
bool isThree = true;
int pointsPerShot = isThree ? 3 : 2;
Console.WriteLine(pointsPerShot);
3
Read it as a question: is it a three-pointer? Then 3, otherwise 2. It does the same job as this if-else, in one line:
bool isThree = true;
int pointsPerShot;
if (isThree)
{
pointsPerShot = 3;
}
else
{
pointsPerShot = 2;
}
Console.WriteLine(pointsPerShot);
3
It's also called the ternary operator, because it has three parts. Keep it for simple choices; when either side needs more than a value, an if reads better.
Many choices: switch expressions
A switch expression turns one value into another. The variable comes first, then switch, then one arm per case: a pattern, =>, and the result.
string dayOfTheWeek = "Tuesday";
string dinner = dayOfTheWeek switch
{
"Monday" => "Soup and sandwiches",
"Tuesday" => "Tacos",
"Wednesday" => "Sushi",
"Saturday" or "Sunday" => "Somewhere new",
_ => "Pasta"
};
Console.WriteLine(dinner);
Tacos
- The arms are separated by commas, and the whole expression ends with
};. orlets one arm match several values._is the discard pattern: it matches anything, likedefaultin a switch statement. Put it last.- There's no
break: each arm is a value, not a block of code.
Matching ranges
A switch expression can also compare with <, >, <= and >=, and join comparisons with and. This is pattern matching. C# checks the arms from the top and uses the first one that matches:
Console.WriteLine(LetterGrade(93));
Console.WriteLine(LetterGrade(85));
Console.WriteLine(LetterGrade(61));
string LetterGrade(int score) => score switch
{
>= 90 => "A",
>= 80 and < 90 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
A
B
D
string LetterGrade(int score) => ... is a method whose body is a single expression. The => replaces { return ...; }. It's handy when a method's whole job is one expression, as it is here.
Which one to use
| You want to | Use |
|---|---|
| Run different code for different conditions | if / else if / else, or a switch statement |
| Pick one of two values | the conditional operator ?: |
| Turn one value into another, with many cases | a switch expression |
Do it: work out the pizza delivery fee
The pizza place charges for delivery by how far away you live. Its website needs the fee for any distance.
The method gets one value:
miles: how far away you live, in whole miles, anint(4). It's never below 0.
The fees:
| Miles | Fee |
|---|---|
| 0 to 2 | $0.00 |
| 3 to 5 | $2.99 |
| 6 to 10 | $4.99 |
| more than 10 | $9.99 |
For example, with 4 miles:
| Check, from the top | With 4 miles |
|---|---|
| 2 miles or less? | No |
| 5 miles or less? | Yes: the fee is $2.99 |
So DeliveryFee(4) returns 2.99m.
Your job: write the method decimal DeliveryFee(int miles) as a switch expression.
- Return the fee from the table, as a
decimal:0m,2.99m,4.99mor9.99m. - The ends of each range count: 2 miles is free, 5 miles is $2.99, and 10 miles is $4.99.
Practiced live on the lesson page: write the C# right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
When a decision's only job is to choose a value, ?: and switch expressions let you say so directly, in fewer lines, with no variable left unset by a forgotten branch.