Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 182 ยท Operators and Control Flow

switch Statements and Expressions

Learn the C# switch statement and the modern switch expression - case labels, fall-through rules, goto case, when guards, exhaustiveness, the discard pattern and when to choose each form.

When one value can lead to many different actions, a long if / else if ladder gets tiring to read. The switch family solves that. C# gives you two forms: the classic switch statement, which runs code depending on a value, and the modern switch expression, which produces a value depending on another value. Both compare one input against a list of cases.

In this lesson you will learn the exact rules of the statement form (they differ from C, C++ and Java in an important way), how to use when guards and goto case, how the compact expression form works, what exhaustiveness means, and how to choose between switch and if. If you are not yet comfortable with conditions, read if, else if and else first.

The classic switch statement

A switch statement evaluates its input once and jumps to the first matching case label. Each section ends with break (or another jump), and an optional default section catches everything that matched nothing.

C# A first switch statement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Change day to 7 to see default run. The default section may appear anywhere in the list, but putting it last is the convention. If you leave it out and nothing matches, the switch simply does nothing.

You can switch on integers, characters, strings, enums, bool and, thanks to patterns, nearly any type. Case labels must be constants (or patterns, see below), and no two labels may match the same value; the compiler reports duplicates.

No implicit fall-through

In C and Java, forgetting break makes execution slide into the next case. That is a famous source of bugs, and C# forbids it. Every section that contains statements must end in a statement that cannot reach the end of the section: break, return, throw, continue or goto. Otherwise the compiler stops you.

C# Missing break (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS0163: Control cannot fall through from one case label ('case 1:') to another. That is a feature: if you want two labels to share code, you stack them with no statements in between.

C# Stacked labels share one section

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Empty labels that sit directly above a section are allowed because they have no statements of their own.

goto case: deliberate fall-through

Sometimes you really do want one case to continue into another. C# makes you say so explicitly with goto case:

C# Explicit jumps with goto case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

goto case and goto default are the only goto forms most programs ever need. The reader can see exactly where control goes, unlike the invisible slide of C-style fall-through. See jumps for the rest of the family.

Patterns and when guards

Case labels are not limited to constants. Since C# 7 they can be patterns: type patterns that also give you a typed variable, relational patterns like >= 90, and combinations with and, or and not (C# 9). A when clause adds an extra boolean condition to any case.

C# Type patterns and when guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Order matters here. The compiler checks cases from top to bottom, so case int n when n < 0 must come before the unguarded case int n. If you put the general case first, the specific one can never be reached, and the compiler reports error CS8120 ("The switch case is unreachable. It has already been handled by a previous case"). The deeper details of patterns live in pattern matching basics and pattern matching in depth.

The switch expression

The statement form is verbose when all you want is to compute a value. The switch expression (C# 8) puts the value first, then the keyword switch, then arms of the form pattern => result separated by commas.

C# Switch statement versus switch expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The differences to remember:

  • It is an expression, so you can assign it, return it, or pass it as an argument.
  • There is no case keyword and no break; each arm is pattern => expression.
  • The default arm is the discard _, which matches anything.
  • Arms are separated by commas, and a trailing comma is allowed.
  • The result type is the best common type of all arm results. If it cannot be determined you may need a target type, for example string s = x switch {...}.

Guards, relational patterns and combining

Arms can use everything the statement form can: relational patterns, and/or/not, property patterns and when guards.

C# A grading switch expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The second function switches on a tuple, so it matches two values at once. That is a very readable replacement for nested if statements. Arms run top to bottom, so the order is again part of the logic: ("US", _) must come after ("US", <= 1m).

Exhaustiveness: what if nothing matches?

A switch expression must cover every possible input. If the compiler can see a gap, it gives a warning (CS8509), and when no arm matches at run time, it throws SwitchExpressionException. For types like int or string, the only way to be exhaustive is a _ arm. For enums, bool and sealed hierarchies the compiler can reason about completeness, but be careful: enums can hold undefined numbers, so a missing arm for an enum still warns.

C# No arm matches (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler warns warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered. and the program prints one and two, then ends with an unhandled System.Runtime.CompilerServices.SwitchExpressionException: Non-exhaustive switch expression failed to match its input. Unmatched value was 3. Treat CS8509 as an error in real projects. Add a _ arm, or better, add an arm that throws when an unexpected value is a real bug:

C#
_ => throw new ArgumentOutOfRangeException(nameof(n), n, "unexpected value"),

A throw expression is allowed as an arm result, so you get an explicit, informative failure instead of the generic exception. The same idea appears in enums and flags, where a switch over an enum should still guard against values that were cast from outside.

Enums: the typical use

C# Switching over an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Without the final _ arm you would get warning CS8524, because an enum variable can contain any number of its underlying type, such as (Light)99. Having the explicit throwing arm documents that decision.

switch statement or switch expression?

Situation Better choice
Compute or return a value Switch expression
Run several statements per case Switch statement
Need goto case or loops with break/continue Switch statement
Map several inputs to a result with patterns Switch expression
Only two outcomes Plain if or the ternary operator

A break inside a switch statement leaves the switch, not an enclosing loop. If you want to leave a loop from inside a switch, use return, a flag, or goto with a label; see break, continue, goto and return.

Performance note

For constants, the compiler generates efficient code: a jump table for dense integer ranges, a hash-based lookup for large string switches, and a chain of comparisons otherwise. You almost never need to optimize a switch by hand, so choose based on readability. For a table of a thousand entries that can change at run time, use a Dictionary (collections) instead of a giant switch.

Prefer the switch expression for pure mappings, and keep arms small. If an arm needs more than a short expression, call a well-named method from it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does C# do when a switch section has statements but no break, return, throw or goto at the end?

    C# has no implicit fall-through. The end of a section must be unreachable, so a missing break is error CS0163.
  2. 2. How do you let two case labels run the same code?

    Stacked labels without statements in between share the section that follows. Omitting break would be a compile error.
  3. 3. In a switch expression, which arm matches every remaining value?

    The switch expression has no default keyword. The discard pattern _ matches anything.
  4. 4. What happens at run time when no arm of a switch expression matches the input?

    A switch expression must produce a value. If no arm matches, it throws System.Runtime.CompilerServices.SwitchExpressionException, and the compiler warns beforehand if it cannot prove exhaustiveness.
  5. 5. Why must case int n when n < 0 be placed before case int n?

    Evaluation order is top to bottom. A general case placed first makes later, narrower cases unreachable, which the compiler reports as an error.

Summary

  • A switch statement jumps to the matching case; each section must end with break, return, throw, continue or goto. There is no accidental fall-through.
  • Stack empty labels to share code, and use goto case for deliberate fall-through.
  • Case labels can be constants or patterns, and when adds a condition. Order matters.
  • A switch expression (value switch { pattern => result, ... }) produces a value; _ is the catch-all.
  • Switch expressions must be exhaustive; add _ => throw ... when an unexpected value is a bug.
  • Use the expression form for mappings, the statement form for several statements per case, and plain if for two outcomes.

Next: while, do-while and for Loops