Lesson 8 of 24

In progress

Course progress

C# and .NET

Switch statements and expressions

Replace chains of else-if with a switch expression, use pattern arms and guards, and let the compiler check exhaustiveness.

C# has two switch forms. The statement runs code for a matching case; the expression produces a value. Most new code wants the expression, because it removes fall-through and assignment in branches.

What you will learn

  • Write a switch expression with pattern arms.
  • Use guards, ranges and type patterns.
  • Know when a switch statement is the better fit.

The expression

int score = 78;
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
_ => "Below C"
};

Arms are tested top to bottom, and the first match wins. _ is the discard pattern and matches anything, so it plays the role of default.

The result is assigned, which is the key difference from the statement form: there is no variable declared before the switch and assigned in every branch, and no possibility of forgetting one.

The statement

switch (command)
{
case "add":
Add();
break;
case "list":
List();
break;
default:
Console.WriteLine("unknown");
break;
}

Each case needs break, return or goto case, because C# forbids falling through from one non-empty case to the next. That rule removes the most common bug in C-style switches.

Use the statement when the arms do different things rather than produce values, especially when they call methods.

Patterns in arms

object value = 42;
string description = value switch
{
int n when n < 0 => "negative",
int n => $"number {n}",
string s when s.Length == 0 => "empty text",
string s => $"text of {s.Length}",
null => "nothing",
_ => "something else"
};

An arm can test a type and bind a variable, add a when guard, or match a constant. Order matters: a general int n arm before a guarded one would swallow every number.

null as a pattern catches the null case without a separate check, which is useful when the input is nullable.

Ranges and combinators

string band = age switch
{
< 13 => "child",
>= 13 and < 20 => "teen",
>= 20 and < 65 => "adult",
_ => "senior"
};

and, or and not compose patterns, and relational patterns work on any comparable type. That is clearer than the equivalent if chain with several && clauses.

Exhaustiveness

enum Status { Pending, Paid, Refunded }
string Label(Status status) => status switch
{
Status.Pending => "Awaiting payment",
Status.Paid => "Paid",
Status.Refunded => "Refunded"
};

With every enum member covered, no discard arm is needed. The compiler warns if a case is missing, so adding a member forces every switch to be updated.

For a boolean, two arms with true and false are exhaustive and read better than a ternary when the labels are words.

Switch on tuples

string Access(bool admin, bool active) => (admin, active) switch
{
(true, true) => "full",
(true, false) => "suspended admin",
(false, true) => "limited",
(false, false) => "blocked"
};

A tuple pattern expresses a table of combinations without nested conditions. Four arms cover the space, and a missing combination is visible at a glance.

Property patterns

record Order(string Status, decimal Total);
string Bucket(Order order) => order switch
{
{ Status: "paid", Total: >= 1000m } => "large paid",
{ Status: "paid" } => "paid",
{ Status: "pending", Total: > 0 } => "awaiting",
{ Total: 0 } => "empty",
_ => "other"
};

The pattern inspects properties without null checks on each, which makes it a compact way to describe business rules. Keep the order from most specific to least, since the first match wins.

When to use which

  • Producing a value from one input: switch expression.
  • Running different actions: switch statement, or a chain of if.
  • Two cases: a ternary or an if.
  • Checking several independent conditions: separate if statements, not a switch.

The anti-pattern is a switch expression with a single arm, or a chain of ten arms that each call a method with different arguments: a dictionary of delegates or a small class per case is often clearer.

Performance

The compiler turns constant arms into a jump table or a hash lookup where it can, so a switch over many constants is comparable to a dictionary lookup and usually faster than a chain of string comparisons.

Do not optimise a switch by hand before measuring. The readable version is usually the fast one, and the compiler is better at this than it looks.

Putting a general type arm before a guarded one, such as int n => ... above int n when n < 0 => .... The guard never runs because the earlier arm matches first.

Write a method that maps a numeric HTTP status to a short label using a switch expression, with arms for 200, 201, 204, 400, 401, 404 and a range for 500 to 599.

Show solution
static string Label(int status) => status switch { 200 => "ok", 201 => "created", 204 => "no content", 400 => "bad request", 401 => "unauthorized", 404 => "not found", >= 500 and <= 599 => "server error", _ => "other" }; Console.WriteLine(Label(201)); Console.WriteLine(Label(503));

The exact codes come first and the range last, because the first matching arm wins. The discard arm covers every code not listed, which keeps the method total without enumerating all of them.

Recap

  • A switch expression returns a value, needs no break, and uses _ as the catch-all.
  • Arms support types, guards, ranges and property patterns, tested in order.
  • Exhaustive enum switches are checked by the compiler, so new members cannot be forgotten.

Next, loops: for, foreach, while and the difference that matters when you modify a collection.

Does C# allow fall-through?
No for non-empty cases. `goto case` is the explicit way to jump to another case.
Can a switch expression throw?
Yes, an arm can be `=> throw new ArgumentException(…)`, which is the usual way to handle an impossible value.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.