Pattern matching in C#: is, switch and patterns
Pattern matching lets you test a value’s type, shape and contents and pull out the parts you need in one expression, instead of chains of casts, null checks and if/else if. This page covers the whole family as it grew from C# 7 to C# 11: the basic is and switch patterns, constants, ranges with relational and logical patterns, the switch expression, property patterns for object graphs, and list patterns for sequences. The examples follow one invented OrdersPortal application: routing messages, classifying parcels and parsing support commands.
Every complete sample is a file-based program: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). All samples on this page were compiled and run with .NET SDK 10.0.115.
Features on this page
Section titled “Features on this page”| Feature | Version | Use it when |
|---|---|---|
| Pattern matching basics | C# 7.0 | You test a type and use the typed value in the same step. |
| Constant patterns | C# 7.0 | You compare against literals, enum members or null. |
| Relational patterns | C# 9 | You branch on ranges and combine conditions with and, or, not. |
| Switch expressions | C# 8 | Each branch produces a value and you want exhaustiveness checks. |
| Property patterns | C# 8 | The decision depends on members of an object, including nested ones. |
| List patterns | C# 11 | The decision depends on the length or positions of a sequence. |
Pattern matching basics
Section titled “Pattern matching basics”Introduced in C# 7.0 (Visual Studio 2017). C# 7.0 added patterns to two places: the is operator and the case labels of a switch statement. A declaration pattern such as message is PaymentReceived payment checks the run-time type and, if it matches, assigns the converted value to a new variable that is definitely assigned only where the match succeeded. That replaces the old as plus null check or is plus cast.
In a switch statement, case labels can now be type patterns with an optional when guard, and the order of cases matters: the first matching case wins, and the compiler reports an error when an earlier case already covers a later one. is null (a constant pattern) and, since C# 9, is not null are the idiomatic null checks, because they cannot be redirected by an overloaded == operator.
object?[] inbox =[ new PaymentReceived(1001, 250.00m), new OrderCancelled(1002, "Customer request"), "heartbeat", 7, null,];
foreach (object? message in inbox){ Console.WriteLine(Describe(message));}
static string Describe(object? message){ if (message is null) return "Skipped an empty message";
if (message is PaymentReceived payment && payment.Amount > 0) return $"Order {payment.OrderId}: payment of {payment.Amount:0.00}";
switch (message) { case OrderCancelled cancelled when cancelled.Reason.Length > 0: return $"Order {cancelled.OrderId}: cancelled ({cancelled.Reason})"; case string text: return $"Text message: {text}"; default: return $"Unknown message type {message.GetType().Name}"; }}
record PaymentReceived(int OrderId, decimal Amount);record OrderCancelled(int OrderId, string Reason);Output:
Order 1001: payment of 250.00Order 1002: cancelled (Customer request)Text message: heartbeatUnknown message type Int32Skipped an empty messagePitfalls:
- A type pattern never matches null.
null is string sis false, so handle null separately (here withis null) or in adefaultbranch. - Scope of the pattern variable.
paymentis only definitely assigned where the match is known to be true; using it in theelsebranch is a compile error. - Type switches over open hierarchies. Long
case Typelists across many classes are often better as a virtual method on the base type.
Constant patterns
Section titled “Constant patterns”Introduced in C# 7.0 (Visual Studio 2017). A constant pattern tests whether a value equals a compile-time constant: a number, string, char, bool, enum member or null. It works with is (status is OrderStatus.OnHold) and in switch statements and expressions, where it is the natural way to map codes to meanings.
Unlike ==, a constant pattern works on an input of type object: boxedCode is 404 checks that the object is a boxed int equal to 404, while boxedCode == 404 does not compile. Constants combine with the C# 9 logical patterns, as in code is 500 or 502 or 503, and since C# 11 a Span<char> or ReadOnlySpan<char> can be matched against a constant string.
int[] carrierCodes = [200, 202, 404, 429, 500];foreach (int code in carrierCodes){ Console.WriteLine($"{code}: {DescribeCarrierResponse(code)}");}
object boxedCode = 404;Console.WriteLine($"boxedCode is 404: {boxedCode is 404}"); // value comparison on object// Console.WriteLine(boxedCode == 404); // error CS0019
OrderStatus status = OrderStatus.OnHold;if (status is OrderStatus.OnHold){ Console.WriteLine("Order needs manual review");}
string? couponCode = null;Console.WriteLine(couponCode is null ? "No coupon" : $"Coupon {couponCode}");
static string DescribeCarrierResponse(int statusCode) => statusCode switch{ 200 => "Label created", 202 => "Label queued", 404 => "Unknown tracking number", 429 => "Rate limited, retry later", _ => "Carrier error",};
enum OrderStatus { New, OnHold, Shipped }Output:
200: Label created202: Label queued404: Unknown tracking number429: Rate limited, retry later500: Carrier errorboxedCode is 404: TrueOrder needs manual reviewNo couponPitfalls:
- Only constants. A variable or a
static readonlyfield cannot be a constant pattern; use awhenguard or==for those. - Strings compare ordinally.
"ready" is "Ready"is false; normalize case first if input can vary.
Relational patterns
Section titled “Relational patterns”Introduced in C# 9 (.NET 5). Relational patterns compare the input against a constant with <, <=, > or >=, and the logical patterns added in the same release combine patterns with and, or and not (plus parentheses for grouping). Together they express ranges directly: hour is >= 9 and < 18 instead of hour >= 9 && hour < 18 with the variable repeated.
In a switch expression, relational arms are checked in order, so a band table reads top to bottom: < 1, then < 5, then <= 30. The compiler knows the arms’ ranges and reports an arm that can never be reached. For double and float it also knows that NaN fails every relational comparison, so a switch over a floating-point value is not exhaustive until something handles NaN.
double[] parcelWeightsKg = [0.4, 2.0, 7.5, 31.0, -1.0, double.NaN];foreach (double weight in parcelWeightsKg){ Console.WriteLine($"{weight,5} kg -> {ShippingBand(weight)}");}
foreach (int hour in new[] { 8, 9, 17, 18 }){ bool open = hour is >= 9 and < 18; Console.WriteLine($"{hour:00}:00 support desk open: {open}");}
static string ShippingBand(double kg) => kg switch{ <= 0 => "invalid weight", < 1 => "letter rate", < 5 => "small parcel", <= 30 => "standard parcel", > 30 => "freight", _ => "not a number", // NaN matches no relational pattern};Output:
0.4 kg -> letter rate 2 kg -> small parcel 7.5 kg -> standard parcel 31 kg -> freight -1 kg -> invalid weight NaN kg -> not a number08:00 support desk open: False09:00 support desk open: True17:00 support desk open: True18:00 support desk open: FalseWithout the _ arm the compiler warns CS8509 (“the pattern ‘double.NaN’ is not covered”) and the call throws SwitchExpressionException for NaN.
Pitfalls:
- Constants only on the right.
kg is < limitdoes not compile whenlimitis a variable; use awhenguard. andbinds tighter thanor.x is > 0 or < -10 and not -20may not mean what it looks like; add parentheses.notwith type patterns.is not nullis clear;is not stringon anobject?is also true for null.
Switch expressions
Section titled “Switch expressions”Introduced in C# 8 (.NET Core 3.0). A switch expression maps an input to a value: input switch { pattern => result, ... }. There are no case, break or return keywords, each arm is an expression, and the whole thing can be an expression-bodied member. Arms accept any pattern, including tuple patterns (also C# 8), which make two-dimensional decision tables readable: (status, paid) switch { (OrderStatus.New, false) => ... }.
The compiler checks exhaustiveness. If some input can reach the end with no matching arm, you get warning CS8509 and, at run time, a SwitchExpressionException that carries the unmatched value. For enums, naming every member still leaves numeric values outside the named set uncovered (warning CS8524), because any integer can be cast to an enum.
var orders = new (OrderStatus Status, bool Paid)[]{ (OrderStatus.New, false), (OrderStatus.New, true), (OrderStatus.Packed, true), (OrderStatus.Shipped, true), (OrderStatus.Cancelled, true),};
foreach (var (status, paid) in orders){ Console.WriteLine($"{status,-9} paid={paid,-5} -> {NextAction(status, paid)}");}
try{ Console.WriteLine(Label((OrderStatus)42));}catch (System.Runtime.CompilerServices.SwitchExpressionException ex){ Console.WriteLine($"Unhandled value: {ex.UnmatchedValue}");}
static string NextAction(OrderStatus status, bool paid) => (status, paid) switch{ (OrderStatus.New, false) => "Wait for payment", (OrderStatus.New, true) => "Send to warehouse", (OrderStatus.Packed, _) => "Book courier", (OrderStatus.Cancelled, true) => "Issue refund", _ => "No action",};
#pragma warning disable CS8524 // unnamed enum values are not handled on purposestatic string Label(OrderStatus status) => status switch{ OrderStatus.New => "New", OrderStatus.Packed => "Packed", OrderStatus.Shipped => "Shipped", OrderStatus.Cancelled => "Cancelled",};#pragma warning restore CS8524
enum OrderStatus { New, Packed, Shipped, Cancelled }Output:
New paid=False -> Wait for paymentNew paid=True -> Send to warehousePacked paid=True -> Book courierShipped paid=True -> No actionCancelled paid=True -> Issue refundUnhandled value: 42Exhaustiveness in C# 15
Section titled “Exhaustiveness in C# 15”C# 15 (.NET 11) adds union types and the closed modifier for class hierarchies. In both cases the compiler knows every case, so a switch expression that handles each case type is exhaustive without a _ arm. This fragment follows the Microsoft Learn example and was not compiled here (needs .NET 11 SDK):
public closed record class GateState;public record class Closed : GateState;public record class Open(float Percent) : GateState;
string Describe(GateState state) => state switch{ Closed => "closed", Open(var percent) => $"{percent}% open", // No warning: every direct descendant of GateState is handled.};Pitfalls:
- A catch-all
_hides new cases. When someone addsOrderStatus.Returned, a_arm silently absorbs it; for closed sets, prefer listing every case and let the warning flag additions. - Arm order matters. A broad arm placed early makes later arms unreachable (error CS8510).
- No statements in arms. If an arm needs several steps, call a method; do not force side effects into the expression.
Property patterns
Section titled “Property patterns”Introduced in C# 8 (.NET Core 3.0). A property pattern { Member: pattern, ... } matches when the input is not null and each listed property or field matches its nested pattern. Because the nested pattern can be any pattern, property patterns are recursive: { Customer: { Country: "PT" }, Total: > 1_000m } checks an order’s customer and total in one test, with null checks built in.
C# 10 (.NET 6) added extended property patterns, which let you write { Customer.IsVip: true } instead of { Customer: { IsVip: true } }. An empty property pattern { } matches any non-null value, which is why is { } value is sometimes used as a “not null, and give me a variable” check.
Order[] orders =[ new(1001, new Customer("Ada", "PT", IsVip: true), 1_500m), new(1002, new Customer("Ben", "US", IsVip: false), 80m), new(1003, new Customer("Chen", "PT", IsVip: false), 2_400m), new(1004, Customer: null, 40m),];
foreach (Order order in orders){ Console.WriteLine($"Order {order.Id}: {ShippingLane(order)}");}
static string ShippingLane(Order order) => order switch{ { Customer.IsVip: true } => "priority", // extended property pattern (C# 10) { Customer: { Country: "PT" }, Total: > 1_000m } => "insured domestic", { Customer.Country: "US" } => "international", { Customer: null } => "on hold: no customer", _ => "standard",};
record Customer(string Name, string Country, bool IsVip);record Order(int Id, Customer? Customer, decimal Total);Output:
Order 1001: priorityOrder 1002: internationalOrder 1003: insured domesticOrder 1004: on hold: no customerPitfalls:
- Property getters run during matching. Keep them cheap and free of side effects; an expensive or lazy-loading getter (for example an ORM navigation property) is evaluated by the pattern.
- Deep nesting hurts readability. Past two or three levels, a well-named helper method or a positional pattern on a record is clearer.
- Business rules hide in patterns. A pricing rule buried in a switch arm is hard to find and test; keep patterns for classification.
List patterns
Section titled “List patterns”Introduced in C# 11 (.NET 7). A list pattern [p1, p2, ...] matches a sequence whose length equals the number of element patterns and whose elements match position by position. The discard _ matches any single element, and a slice pattern .. matches zero or more elements; .. var rest captures that slice. At most one slice is allowed per list pattern.
List patterns work on any type that is countable (Length or Count) and indexable (an indexer taking Index or int), such as arrays, List<T> and spans; capturing a slice also needs range support. They do not work on plain IEnumerable<T>. They shine for small structured inputs: command lines, split strings, or “first and last” checks.
string[] commands =[ "ship 1001", "refund 1002 19.99", "note 1003 leave at the front desk", "", "cancel",];
foreach (string line in commands){ string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); Console.WriteLine($"'{line}' -> {Handle(parts)}");}
int[] dailyOrders = [12, 15, 9, 30];if (dailyOrders is [var first, .., var last] && last > first * 2){ Console.WriteLine($"Orders jumped from {first} to {last}");}
static string Handle(string[] parts) => parts switch{ [] => "empty command", ["ship", var id] => $"ship order {id}", ["refund", var id, var amount] => $"refund {amount} on order {id}", ["note", var id, .. var words] => $"note on {id}: {string.Join(' ', words)}", [var verb, ..] => $"unknown command '{verb}'",};Output:
'ship 1001' -> ship order 1001'refund 1002 19.99' -> refund 19.99 on order 1002'note 1003 leave at the front desk' -> note on 1003: leave at the front desk'' -> empty command'cancel' -> unknown command 'cancel'Orders jumped from 12 to 30Pitfalls:
- Slices allocate on arrays.
.. var wordson an array creates a new array; on aSpan<T>it is a cheap slice. - Not for large data. Use list patterns for shape checks on small inputs, not as a replacement for LINQ or loops over big collections.
Choosing between them
Section titled “Choosing between them”- Testing one type and using it: a declaration pattern with
is. - Mapping inputs to values: a
switchexpression; use aswitchstatement only when arms need several statements. - Ranges and thresholds: relational patterns with
and/or; values known only at run time go in awhenguard. - Decisions on object state: property patterns; on sequence shape: list patterns.
- Closed sets (enums, records you own, C# 15 unions and closed hierarchies): list every case and avoid
_so the compiler flags additions.
Interview questions
Section titled “Interview questions”What is the difference between x is null and x == null?
is null always performs a reference (or Nullable<T>) null test. == null calls a user-defined == operator if the type overloads one, which can return something unexpected.
What happens when no arm of a switch expression matches?
The compiler warns (CS8509) if it can see an unhandled input, and at run time a SwitchExpressionException is thrown with the unmatched value. A switch statement, in contrast, simply does nothing.
Why can a switch expression over an enum warn even when all members are listed?
Any integer can be cast to an enum, so values outside the named members are possible. The compiler reports CS8524 for those; add a _ arm that throws, or suppress deliberately.
What does { } match?
Any non-null value. if (order.Customer is { } customer) is a null check that also introduces a variable.
Which types support list patterns?
Types that are countable (Length or Count) and indexable (this[int] or this[Index]); slice patterns that capture also need a range indexer or Slice. Arrays, List<T>, Span<T> and string qualify; IEnumerable<T> does not.
Senior scenario: OrdersPortal has a 300-line if/else chain deciding shipping lanes from country, VIP status, weight and total. Would you convert it to one big switch expression?
Convert it to a table-shaped switch expression only if the rules are stable and owned by developers: property and relational patterns make each rule one readable line and the compiler catches unreachable arms. If the business changes the rules often, or different markets need different rules, move them to data or a rules component with its own tests, and keep pattern matching for the small, structural decisions such as parsing input and dispatching message types.
Related pages
Section titled “Related pages”- Null handling in C#: nullable types and the null operators that pair with
is nullchecks. - Collections and queries: collection expressions and LINQ, which complement list patterns.
- C# 15 release guide: union types and closed hierarchies.
- C# version history