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 : 2 is 3 when isThree is true, 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, or lets one arm match several values, and _ matches anything, so it goes last.
  • Arms can compare with <, >, <= and >= and join them with and. C# uses the first arm that matches.
  • To run different code, use if or a switch statement; 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 };.
  • or lets one arm match several values.
  • _ is the discard pattern: it matches anything, like default in 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

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.

Key terms

Cheat sheets