Switch expressions and modern patterns
suggest changeThe classic switch statement compares a value against constants, and every case needs a break. Since C# 8 there's also a switch expression: it evaluates to a value, has no case or break, and every arm is a pattern, not just a constant. Later versions added more kinds of patterns, so most if/else if chains can now be written as one switch expression.
Versions:
- C# 7 (.NET Core 2.0): type patterns in
isandcase(case Circle c:),whenguards; see Pattern Matching - C# 8 (.NET Core 3.0): switch expressions, property patterns
{ Length: 0 }, positional and tuple patterns - C# 9 (.NET 5): relational patterns (
< 0,>= 'a'), logical patterns (and,or,not, sois not null), type patterns without a variable (int =>) - C# 10 (.NET 6): extended property patterns
{ Customer.Address.City: "Paris" } - C# 11 (.NET 7): list patterns
[first, .. rest]
List patterns and positional patterns are covered in Destructuring, so this article only touches on them.
The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. Nullable reference types are on, as in new projects. All output comes from real runs.
From switch statement to switch expression
Here's the same logic written both ways:
static string Name(DayOfWeek day)
{
string name;
switch (day)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
name = "weekend";
break;
default:
name = "workday";
break;
}
return name;
}
static string Name2(DayOfWeek day) => day switch
{
DayOfWeek.Saturday or DayOfWeek.Sunday => "weekend",
_ => "workday",
};
Console.WriteLine($"{Name(DayOfWeek.Sunday)} {Name2(DayOfWeek.Sunday)}");
Console.WriteLine($"{Name(DayOfWeek.Monday)} {Name2(DayOfWeek.Monday)}");
weekend weekend
workday workday
The syntax rules:
- The value being tested comes before the
switchkeyword:day switch { ... }. - Each arm is
pattern => expression, and arms are separated by commas. A trailing comma after the last arm is allowed. _is the discard pattern. It matches anything and plays the role ofdefault.- Arms are tried from top to bottom and the first match wins.
- Each arm is a single expression. If you need several statements, use a switch statement (see below) or call a method.
- The whole thing is an expression, so you can return it, assign it, pass it as an argument or use it as an expression-bodied member, as above.
throw is an expression too, which is handy for the "can't happen" arm. Here is a function that mixes several kinds of patterns, all explained below:
static int Days(int month, int year) => month switch
{
2 when DateTime.IsLeapYear(year) => 29,
2 => 28,
4 or 6 or 9 or 11 => 30,
>= 1 and <= 12 => 31,
_ => throw new ArgumentOutOfRangeException(nameof(month), month, "must be 1-12"),
};
Console.WriteLine(Days(2, 2024));
Console.WriteLine(Days(2, 2025));
Console.WriteLine(Days(9, 2025));
Console.WriteLine(Days(12, 2025));
try { Days(13, 2025); }
catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); }
29
28
30
31
must be 1-12 (Parameter 'month')
Actual value was 13.
Exhaustiveness
A switch expression must produce a value for every input. If the compiler can find an input that no arm handles, it warns, and at runtime an unmatched value throws SwitchExpressionException.
Enums are a common surprise. Handling every named member isn't enough, because any int can be cast to an enum:
Console.WriteLine(Hex(Color.Green));
Console.WriteLine(Hex((Color)7));
static string Hex(Color c) => c switch
{
Color.Red => "#ff0000",
Color.Green => "#00ff00",
Color.Blue => "#0000ff",
};
enum Color { Red, Green, Blue }
warning CS8524: The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. For example, the pattern '(Color)3' is not covered.
#00ff00
Unhandled exception. System.Runtime.CompilerServices.SwitchExpressionException: Non-exhaustive switch expression failed to match its input.
Unmatched value was 7.
Add _ => throw new ArgumentOutOfRangeException(nameof(c)) to state what should happen and get rid of the warning. (If you leave out a named member, you get the stronger warning CS8509, which tells you which member is missing. Don't hide that one with _.)
With nullable reference types enabled, null counts too:
static int Len(string? s) => s switch
{
string t => t.Length,
};
warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern 'null' is not covered.
C# has no closed (sealed) hierarchies, so a switch over the subclasses of an abstract class always needs a _ arm, even if you've listed every subclass that exists today.
The compiler also rejects arms that can never match because earlier arms already cover them:
static string Size(int n) => n switch
{
> 0 => "positive",
> 100 => "big",
_ => "other",
};
error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.
Put the more specific arm first.
Type patterns
A type pattern tests the runtime type. Add a name to also get a typed variable (int i). In C# 9 and later you can leave out the name when you only care about the type (IEnumerable<int> =>). Patterns nest, so string { Length: 0 } tests the type and a property in one go:
static string Describe(object? o) => o switch
{
null => "null",
int i => $"int {i}",
string { Length: 0 } => "empty string",
string s => $"string of length {s.Length}",
IEnumerable<int> => "a sequence of ints",
_ => $"something else: {o.GetType().Name}",
};
Console.WriteLine(Describe(null));
Console.WriteLine(Describe(42));
Console.WriteLine(Describe(""));
Console.WriteLine(Describe("hello"));
Console.WriteLine(Describe(new List<int> { 1, 2 }));
Console.WriteLine(Describe(3.14));
null
int 42
empty string
string of length 5
a sequence of ints
something else: Double
A type pattern never matches null, which is why the null arm is separate. In the _ arm the compiler knows o isn't null, because the first arm already handled null, so o.GetType() gives no warning.
Relational patterns
<, <=, > and >= followed by a constant (C# 9) compare the input with that constant. Since arms are tried in order, a sorted list of thresholds reads like a lookup table:
static string Classify(double temp) => temp switch
{
< 0 => "freezing",
< 10 => "cold",
< 20 => "mild",
< 30 => "warm",
_ => "hot",
};
foreach (var t in new[] { -5.0, 0, 15.5, 29.9, 35, double.NaN })
Console.WriteLine($"{t}: {Classify(t)}");
-5: freezing
0: cold
15.5: mild
29.9: warm
35: hot
NaN: hot
Watch the last line. Every comparison with NaN is false, so NaN falls through to _. If that matters, add a double.NaN => ... arm at the top (constant patterns do match NaN).
Relational patterns work with any type that has constants: integers, floating point, decimal, char, and enums.
Logical patterns: and, or, not
and, or and not combine patterns (C# 9). Use them to build ranges and sets:
static string Status(int code) => code switch
{
200 => "OK",
201 or 204 => "success, no body to show",
>= 200 and < 300 => "other success",
301 or 302 or 307 or 308 => "redirect",
404 => "not found",
>= 400 and < 500 => "client error",
>= 500 and < 600 => "server error",
_ => "unknown",
};
foreach (var c in new[] { 200, 204, 226, 308, 404, 429, 503, 42 })
Console.WriteLine($"{c}: {Status(c)}");
200: OK
204: success, no body to show
226: other success
308: redirect
404: not found
429: client error
503: server error
42: unknown
Precedence is not, then and, then or, and you can use parentheses for clarity. Patterns work with is too, not just in switch:
static string Kind(char c) => c switch
{
>= 'a' and <= 'z' or >= 'A' and <= 'Z' => "letter",
>= '0' and <= '9' => "digit",
' ' or '\t' or '\n' => "whitespace",
_ => "other",
};
foreach (var c in "aZ7 ?")
Console.WriteLine($"'{c}' {Kind(c)}");
static bool IsLetter(char c) => c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z');
Console.WriteLine(IsLetter('q'));
'a' letter
'Z' letter
'7' digit
' ' whitespace
'?' other
True
x is >= 1 and <= 12 evaluates x only once, unlike x >= 1 && x <= 12. That matters when x is a method call or a long expression like order.Lines[i].Quantity.
is null and is not null
not makes the most popular pattern of all possible:
string? name = Environment.GetEnvironmentVariable("NO_SUCH_VAR");
if (name is null) Console.WriteLine("name is null");
if (name is not null) Console.WriteLine($"name is {name}");
object o = "text";
if (o is not string) Console.WriteLine("not a string");
else Console.WriteLine("it's a string");
// not with a declaration: the variable is assigned when the pattern fails
if (o is not string s)
return;
Console.WriteLine(s.ToUpper());
name is null
it's a string
TEXT
The last part is a guard clause: after if (o is not string s) return;, the variable s is definitely assigned for the rest of the method.
Prefer is null / is not null over == null / != null. A class can overload ==, while is null always checks the reference:
var bad = new Weird();
Console.WriteLine(bad == null);
Console.WriteLine(bad is null);
class Weird
{
public static bool operator ==(Weird? a, Weird? b) => true;
public static bool operator !=(Weird? a, Weird? b) => false;
public override bool Equals(object? obj) => true;
public override int GetHashCode() => 0;
}
True
False
Overloads this broken are rare, but real ones exist: Unity's UnityEngine.Object overloads == so that a destroyed object compares equal to null. See Nullable reference types for how is not null also drives the compiler's null-state analysis.
Property patterns
A property pattern { Name: pattern, ... } matches if the value is not null and each listed property matches its sub-pattern. The sub-patterns can be any pattern: constants, relational, or, var, another property pattern.
C# 10 added extended property patterns: { Customer.Address.Country: "US" } instead of { Customer: { Address: { Country: "US" } } }. Each step of the dotted path also checks for null, so a missing customer or address just doesn't match. It doesn't throw.
var orders = new[]
{
new Order(1, new Customer("Ann", new Address("Berlin", "DE")), 120m, Status.Paid),
new Order(2, new Customer("Bob", new Address("Austin", "US")), 15m, Status.Paid),
new Order(3, new Customer("Cid", new Address("Paris", "FR")), 0m, Status.Cancelled),
new Order(4, new Customer("Dee", null), 40m, Status.Pending),
};
foreach (var o in orders)
Console.WriteLine($"#{o.Id}: {Shipping(o)}");
static string Shipping(Order o) => o switch
{
{ Status: Status.Cancelled } => "nothing to ship",
{ Customer.Address: null } => "missing address",
{ Customer.Address.Country: "US", Total: >= 50 } => "free US shipping",
{ Customer.Address.Country: "US" } => "US flat rate",
{ Customer.Address.Country: "DE" or "FR" or "NL", Total: var t } => $"EU shipping on {t}",
_ => "international",
};
enum Status { Pending, Paid, Cancelled }
record Address(string City, string Country);
record Customer(string Name, Address? Address);
record Order(int Id, Customer Customer, decimal Total, Status Status);
#1: EU shipping on 120
#2: US flat rate
#3: nothing to ship
#4: missing address
var t always matches and binds the property to a variable, so you can use it in the arm's result.
The empty property pattern { }
{ } lists no properties, so it only checks "not null". x is { } v means "x isn't null, and call it v". That's useful when x is a longer expression you don't want to repeat:
object?[] values = ["hi", null, 5];
foreach (var v in values)
{
if (v is { } notNull)
Console.WriteLine($"got {notNull.GetType().Name}");
else
Console.WriteLine("got null");
}
// typical use: test and bind a nullable property in one step
var user = new User("ann", new Profile("Ann Smith"));
if (user.Profile is { DisplayName: { Length: > 0 } display })
Console.WriteLine($"Hello, {display}");
record Profile(string? DisplayName);
record User(string Login, Profile? Profile);
got String
got null
got Int32
Hello, Ann Smith
The last if replaces user.Profile != null && user.Profile.DisplayName != null && user.Profile.DisplayName.Length > 0. Inside it, display is a non-nullable string.
when guards
When a pattern can't express a condition, for example because it compares two properties with each other or calls a method, add when followed by a boolean expression. The arm matches only if the pattern matches and the guard is true:
foreach (var s in new Shape[] { new Circle(1), new Rect(2, 2), new Rect(2, 5), new Triangle(3, 4, 5) })
Console.WriteLine($"{s}: area {Area(s):F2}, {Describe(s)}");
static double Area(Shape s) => s switch
{
Circle c => Math.PI * c.R * c.R,
Rect r => r.W * r.H,
Triangle(var a, var b, var c) => Heron(a, b, c),
_ => throw new NotSupportedException(s.GetType().Name),
};
static double Heron(double a, double b, double c)
{
var p = (a + b + c) / 2;
return Math.Sqrt(p * (p - a) * (p - b) * (p - c));
}
static string Describe(Shape s) => s switch
{
Rect r when r.W == r.H => "a square",
Rect => "a rectangle",
Triangle t when t.A * t.A + t.B * t.B == t.C * t.C => "a right triangle",
Circle { R: > 10 } => "a big circle",
_ => "a shape",
};
abstract record Shape;
record Circle(double R) : Shape;
record Rect(double W, double H) : Shape;
record Triangle(double A, double B, double C) : Shape;
Circle { R = 1 }: area 3.14, a shape
Rect { W = 2, H = 2 }: area 4.00, a square
Rect { W = 2, H = 5 }: area 10.00, a rectangle
Triangle { A = 3, B = 4, C = 5 }: area 6.00, a right triangle
Triangle(var a, var b, var c) is a positional pattern; it uses the Deconstruct method that records get for free. Abstract records and type patterns together give you sum types (also called discriminated unions): the data lives in small records, and the operations are switch expressions over them.
Prefer a pattern over a guard when you can (Circle { R: > 10 }, not Circle c when c.R > 10). The compiler can check patterns for exhaustiveness and unreachable arms, but it can't see inside a when expression, so an arm with a guard never counts as covering its pattern.
Replacing if/else chains
A chain of if/return that looks at the same few values is usually a switch expression. To branch on several values, switch on a tuple you build on the spot:
static decimal DiscountOld(Customer c, decimal total)
{
if (c == null)
throw new ArgumentNullException(nameof(c));
if (c.IsEmployee)
return 0.30m;
if (c.Tier == Tier.Gold && total >= 100)
return 0.15m;
if (c.Tier == Tier.Gold)
return 0.10m;
if (c.Tier == Tier.Silver && total >= 100)
return 0.05m;
if (c.YearsActive > 5)
return 0.02m;
return 0m;
}
static decimal Discount(Customer c, decimal total) => (c, total) switch
{
(null, _) => throw new ArgumentNullException(nameof(c)),
({ IsEmployee: true }, _) => 0.30m,
({ Tier: Tier.Gold }, >= 100) => 0.15m,
({ Tier: Tier.Gold }, _) => 0.10m,
({ Tier: Tier.Silver }, >= 100) => 0.05m,
({ YearsActive: > 5 }, _) => 0.02m,
_ => 0m,
};
var customers = new[]
{
new Customer(Tier.Gold, false, 1),
new Customer(Tier.Silver, false, 7),
new Customer(Tier.None, true, 0),
};
foreach (var c in customers)
foreach (var total in new[] { 50m, 150m })
Console.WriteLine($"{c.Tier,-6} employee={c.IsEmployee,-5} total={total,3}: {DiscountOld(c, total):P0} {Discount(c, total):P0}");
enum Tier { None, Silver, Gold }
record Customer(Tier Tier, bool IsEmployee, int YearsActive);
Gold employee=False total= 50: 10% 10%
Gold employee=False total=150: 15% 15%
Silver employee=False total= 50: 2% 2%
Silver employee=False total=150: 5% 5%
None employee=True total= 50: 30% 30%
None employee=True total=150: 30% 30%
The switch version reads as a table of rules. The compiler also tells you when a new rule is unreachable, and it doesn't allocate a tuple, because tuple patterns are compiled into plain comparisons. See Destructuring for more tuple and positional pattern examples, like FizzBuzz.
Not every chain should become a switch, though. If the conditions test unrelated things, have side effects, or each branch runs several statements, plain if/else is clearer.
Patterns in switch statements
All of these patterns also work after case in a switch statement. Use one when the branches run statements rather than produce a value:
Handle(new Login("ann"));
Handle(new Upload("ann", 12_000_000));
Handle(new Upload("bob", 300));
Handle(new Logout("ann"));
static void Handle(Event e)
{
switch (e)
{
case Login { User: var u }:
Console.WriteLine($"{u} logged in");
break;
case Upload { Bytes: > 10_000_000 } up:
Console.WriteLine($"{up.User}: upload too big ({up.Bytes:N0} bytes)");
Console.WriteLine(" rejected");
break;
case Upload up when up.User.StartsWith('b'):
Console.WriteLine($"{up.User}: uploading {up.Bytes} bytes to the b-bucket");
break;
case Upload up:
Console.WriteLine($"{up.User}: uploading {up.Bytes} bytes");
break;
default:
Console.WriteLine($"ignored {e}");
break;
}
}
abstract record Event;
record Login(string User) : Event;
record Upload(string User, long Bytes) : Event;
record Logout(string User) : Event;
ann logged in
ann: upload too big (12,000,000 bytes)
rejected
bob: uploading 300 bytes to the b-bucket
ignored Logout { User = ann }
Unlike a switch expression, a switch statement isn't checked for exhaustiveness. An unmatched value just does nothing.
Gotchas
A switch expression can't be a statement. It has to produce a value that's used:
n switch { 3 => Console.WriteLine("three"), _ => Console.WriteLine("other") };
error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
The arms need a common type, or a target type. var x = b switch { true => 1, false => "one" }; fails with error CS8506: No best type was found for the switch expression. Since C# 9 the switch is target-typed, so giving the result a type fixes it:
bool b = args.Length > 5;
int? count = b switch { true => 1, false => null };
object o = b switch { true => 1, false => "one" };
Console.WriteLine(count is null);
Console.WriteLine(o);
True
one
Patterns need constants. You can't compare with a variable: limit => ... gives error CS9135: A constant value of type 'int' is expected. Use a guard (var n when n == limit) or a relational pattern with a const.
or and not can't declare variables. o is int i or long i gives error CS8780: A variable may not be declared within a 'not' or 'or' pattern. Write separate arms instead.
not binds tighter than or. x is not 1 or 2 means (not 1) or 2, which is true for 2. The compiler flags it:
int x = 2;
Console.WriteLine(x is not 1 or 2);
Console.WriteLine(x is not (1 or 2));
warning CS9336: The pattern is redundant.
True
False
You almost always mean is not (1 or 2).
Don't count on evaluation order. The compiler turns all arms into one decision tree. It may read a property once and reuse it, or test arms in a different order than you wrote them. Properties and when guards in patterns should be cheap and have no side effects.