The Analogy: The Sorting Rack
An if / else if chain is a queue of guards, each asking their own question in turn. A switch is a sorting rack in a post room: one item, many labelled pigeonholes, and the sorter goes straight to the right hole instead of walking past every other one.
That difference is real and not only stylistic. When a chain tests the same value against many alternatives, a switch says so in the code, and the compiler can turn it into a jump table or a hash lookup rather than a sequence of comparisons. More importantly for you, it can check your work: a switch over an enum will warn about the member you forgot.
Modern C# has two forms. The switch statement chooses which code to run. The switch expression, added in C# 8, chooses which value to produce, and it is the one you will reach for most often because it fits on one line per case and cannot fall through.
Syntax or Core Structure
using System;
class Program
{
static void Main()
{
string command = "delete";
switch (command)
{
case "add":
case "create":
Console.WriteLine("creating");
break;
case "delete":
Console.WriteLine("deleting");
break;
case "help":
Console.WriteLine("showing help");
break;
default:
Console.WriteLine($"unknown: {command}");
break;
}
int day = 6;
string kind = day switch
{
1 or 2 or 3 or 4 or 5 => "weekday",
6 or 7 => "weekend",
_ => "invalid",
};
Console.WriteLine($"day {day} is a {kind}");
object value = 42;
string described = value switch
{
null => "nothing",
int n when n > 100 => $"big int {n}",
int n => $"int {n}",
string s => $"string of length {s.Length}",
_ => "something else",
};
Console.WriteLine(described);
}
}
Output:
deleting
day 6 is a weekend
int 42
The two forms differ in shape as well as purpose:
| Switch statement | Switch expression | |
|---|---|---|
| Introduced | C# 1 | C# 8 |
| Produces | nothing; it runs code | a value |
| Case syntax | case X: … break; | X => result, |
| Fallback | default: | _ => |
| Missing fallback | value simply falls through | throws SwitchExpressionException |
| Multiple statements | yes | no — use a method call |
case "add": case "create": stacking two labels is how C# expresses "either of these", because it has no implicit fall-through: an ordinary case body must end with break, return, throw or goto. In the expression form the same idea is written "add" or "create" =>.
Technical Depth: Patterns Are the Real Feature
A case label used to be limited to a compile-time constant. Since C# 7 it can be a pattern, and that is what turned switch from a tidier if chain into the main dispatch tool in the language.
| Pattern | Example | Matches |
|---|---|---|
| Constant | case 404: | that exact value, including null |
| Relational | >= 500 | a comparison |
| Logical | >= 200 and < 300, 404 or 410, not null | combinations |
| Type | int n, string s | the run-time type, binding a variable |
| Property | { Total: > 100m } | a member of the object |
| Tuple | (State.Draft, Event.Place) | several values at once |
| List | [], [_, ..] | array or list shape (C# 11) |
| Discard | _ | anything |
static string Http(int code) => code switch
{
200 or 201 or 204 => "success",
>= 300 and < 400 => "redirect",
401 or 403 => "denied",
404 => "not found",
>= 500 => "server error",
_ => $"unhandled: {code}",
};
Guards and arm order
decimal Fee(decimal amount) => amount switch
{
var a when a < 0m => throw new ArgumentOutOfRangeException(nameof(amount)),
0m => 0m,
< 100m => 1.50m,
_ => amount * 0.01m,
};
Arms are tested top to bottom, so the specific must precede the general exactly as in an if chain. Put int n above int n when n > 100 and the guarded arm becomes dead code — the compiler will not always tell you, because the guard makes it hard to prove.
A when clause is an arbitrary boolean, so it can express anything a pattern cannot. Reach for a pattern first and a guard only when the pattern runs out.
Exhaustiveness, and what the compiler checks
enum Level { Low, Medium, High }
// Warning CS8509: not all possible values are covered
string Name(Level l) => l switch
{
Level.Low => "low",
Level.Medium => "medium",
};
Add Level.High and the warning disappears. This is the strongest practical argument for switching over an enum: add a member six months later and every unexhaustive switch in the solution lights up.
Because an enum is really an int, a value outside the declared members is still possible — (Level)99 is legal. So end an enum switch with an arm that throws rather than one that guesses:
_ => throw new ArgumentOutOfRangeException(nameof(l), l, "unknown level"),
The scope trap in a statement switch
switch (kind)
{
case "a":
int n = 1; // this name now belongs to the whole switch block
break;
case "b":
int n = 2; // CS0128: already defined in this scope
break;
}
switch (kind)
{
case "a":
{
int n = 1; // braces give each case its own scope
break;
}
case "b":
{
int n = 2;
break;
}
}
All the cases of a statement switch share one scope, which surprises everyone once. Brace the case body, or better, move the work into a method.
goto case
case "retry":
attempts++;
goto case "send"; // deliberate, explicit fall-through
case "send":
Send();
break;
C# removed implicit fall-through and gave back goto case for the rare occasion it was wanted. It is legal, it is readable enough, and it is worth using instead of duplicating a case body.
Real World Example: An Order State Machine
A state machine is the case switch was invented for: a fixed set of states, a fixed set of events, and a table saying which pairs are allowed. A tuple pattern lets that table be the code.
using System;
enum State { Draft, Placed, Paid, Shipped, Cancelled }
enum Event { Place, Pay, Ship, Cancel }
class Program
{
static State Next(State current, Event e) => (current, e) switch
{
(State.Draft, Event.Place) => State.Placed,
(State.Placed, Event.Pay) => State.Paid,
(State.Paid, Event.Ship) => State.Shipped,
(State.Draft or State.Placed or State.Paid, Event.Cancel) => State.Cancelled,
_ => current, // anything else is not a legal transition
};
static string Describe(State s) => s switch
{
State.Draft => "not submitted",
State.Placed => "awaiting payment",
State.Paid => "awaiting despatch",
State.Shipped => "on its way",
State.Cancelled => "cancelled",
_ => throw new ArgumentOutOfRangeException(nameof(s), s, "unknown state"),
};
static void Main()
{
State state = State.Draft;
Event[] script = { Event.Place, Event.Pay, Event.Pay, Event.Ship, Event.Cancel };
Console.WriteLine($"{"event",-8}{"state",-11}meaning");
Console.WriteLine($"{"start",-8}{state,-11}{Describe(state)}");
foreach (Event e in script)
{
State before = state;
state = Next(state, e);
string mark = state == before ? " (ignored)" : "";
Console.WriteLine($"{e,-8}{state,-11}{Describe(state)}{mark}");
}
}
}
Output:
event state meaning
start Draft not submitted
Place Placed awaiting payment
Pay Paid awaiting despatch
Pay Paid awaiting despatch (ignored)
Ship Shipped on its way
Cancel Shipped on its way (ignored)
The second Pay and the final Cancel change nothing: neither (Paid, Pay) nor (Shipped, Cancel) appears in the table, so both fall to _ => current. Comparing the state before and after is how the caller detects that an event was refused.
The transition table is the whole method. Six lines describe the entire legal behaviour of an order, and adding a rule means adding a line. The equivalent nested if — outer switch on state, inner switch on event — is three times the size and much harder to check against a specification.
(State.Draft or State.Placed or State.Paid, Event.Cancel) collapses three rules into one arm. Cancellation is legal from any state that has not shipped, and the or pattern says exactly that.
Describe throws on an unknown state rather than returning "unknown". Since (State)99 is a legal State value at run time, the impossible case needs to fail loudly. Adding a sixth member to the enum without extending Describe also produces compiler warning CS8509 at every switch that forgot it.
{e,-8} formats an enum by calling ToString() and then padding, which is why the columns line up without any manual spacing.
Common Mistakes
- Forgetting
break. A statement switch gives CS0163, "control cannot fall through from one case label to another". C# will not let you rely on fall-through the way C does; stack the labels or usegoto casewhen you actually want it. - Using a variable as a case label.
case maxValue:fails unlessmaxValueis aconst, because a constant pattern needs a compile-time value. Use awhenguard:case var v when v == maxValue:. - Omitting
_from a switch expression. Nothing complains at build time if the compiler cannot prove the arms are exhaustive, and then an unmatched input throwsSwitchExpressionExceptionin production. Always end with_, even if it throws. - Ordering arms from general to specific.
int nbeforeint n when n > 100makes the guarded arm unreachable, and_placed anywhere but last swallows everything below it. - Declaring the same variable in two cases. All cases of a statement switch share one scope, so the second
int nis CS0128. Brace each case body. - Trusting an enum to hold only its declared members.
(Level)99casts cleanly, so an enum switch without a throwing fallback can silently return the wrong answer for data that came from a database or a request. - Switching on
double. Constant patterns use equality, and floating-point equality rarely holds. Use relational patterns (< 0.5) ordecimal. - Putting statements in a switch expression arm. Each arm must be a single expression. If a case needs three lines of work, call a method from the arm — and remember the whole expression ends with a semicolon, unlike a switch statement's closing brace.
Best Practices
- Prefer the switch expression whenever the goal is to produce a value. It is shorter, it cannot fall through, and it forces every arm to return the same kind of thing.
- Switch over enums rather than over strings or magic numbers, and let warning CS8509 tell you which switches to revisit when the enum grows.
- End every enum or type switch with an arm that throws
ArgumentOutOfRangeException, passingnameof(x)and the offending value so the message names the culprit. - Use tuple patterns instead of nesting one switch inside another. A transition table reads far better as
(state, event) switch. - Keep arms to one line. When an arm grows, extract a well-named method and call it from the arm; the switch then remains a readable index of behaviour.
- Use
orandandpatterns instead of repeating a body across several stacked labels, and relational patterns instead of numericifchains. - Reach for a
switchonce anifchain tests the same value three or more times — and stay withifwhen the conditions test different values, which a switch cannot express. - Group the arms in a deliberate order — happy path first, then errors, then
_— so a reviewer reads the intended behaviour before the edge cases.
Practice Exercises
- Write
static string Http(int code)as a switch expression handling 200, 201, 204, the 3xx range, 401, 403, 404, the 5xx range, and anything else. Print the result for{ 200, 204, 301, 403, 404, 418, 503 }. - Convert a four-branch
if / else ifchain of your own into a switch expression, then into a switch statement, and note which of the three you find easiest to read and why. - Extend the order state machine with a
Refundevent that is legal only fromShippedand leads to a newRefundedstate. Add the enum member, extendDescribe, and confirm the compiler warns before you do. - Write a
static string Classify(object? o)using type, constant and property patterns that distinguishes null, an empty string, a non-empty string, a negativeint, a non-negativeint, and anything else. Test it with at least seven values includingnull.