C# pattern matching
last modified November 15, 2026
This article shows how to use pattern matching in C#. We cover type,
constant, relational, logical, property, positional, var, and list
patterns, the when guard, and exhaustiveness checks.
Pattern matching tests whether a value has a certain shape and,
if it does, extracts data from it. A pattern can check the type of a value,
compare it to a constant or a range, look inside its properties, or match
the elements of a sequence. Patterns are used in three places: the
is expression, the switch expression, and the
case labels of the switch statement.
Pattern matching replaces long chains of casts, if statements,
and null checks with short declarative code. The compiler also checks
patterns: it reports cases that can never match and warns when a
switch expression does not cover all possible input values.
Type patterns with is
The simplest pattern is a declaration pattern. It checks the runtime type of a value and, on success, assigns the converted value to a new variable.
object[] values = [42, "falcon", 3.14, true, null!, 'c'];
foreach (var val in values)
{
if (val is int n)
{
Console.WriteLine($"int: {n * 2}");
}
else if (val is string s)
{
Console.WriteLine($"string of length {s.Length}");
}
else if (val is null)
{
Console.WriteLine("null value");
}
else
{
Console.WriteLine($"other: {val.GetType().Name}");
}
}
We go through an array of objects and test the type of each element.
if (val is int n)
{
Console.WriteLine($"int: {n * 2}");
}
If val holds a boxed int, the is
expression returns true and the unboxed value is stored in
n. The variable n is definitely assigned only
inside the if block. Without patterns, we would have to test
the type with is first and then cast the value.
else if (val is null)
The null constant pattern checks for null. Unlike
val == null, it cannot be affected by an overloaded
== operator. Note that a type pattern never matches
null; the null element falls through the int and
string tests.
$ dotnet run int: 84 string of length 6 other: Double other: Boolean null value other: Char
The switch expression
The switch expression evaluates patterns from top to bottom
and returns the result of the first arm whose pattern matches. It is the
most common place for pattern matching.
object[] shapes = [new Circle(2), new Rectangle(3, 4), new Square(5), "text", null!];
foreach (var shape in shapes)
{
Console.WriteLine(Describe(shape));
}
static string Describe(object? shape) => shape switch
{
Circle c => $"circle with area {Math.PI * c.Radius * c.Radius:F2}",
Square s => $"square with area {s.Side * s.Side}",
Rectangle r => $"rectangle with area {r.Width * r.Height}",
null => "no shape",
_ => $"unknown object of type {shape.GetType().Name}"
};
record Circle(double Radius);
record Rectangle(double Width, double Height);
record Square(double Side);
We compute the area of different shapes. Each shape is a record.
static string Describe(object? shape) => shape switch
{
Circle c => $"circle with area {Math.PI * c.Radius * c.Radius:F2}",
Square s => $"square with area {s.Side * s.Side}",
Rectangle r => $"rectangle with area {r.Width * r.Height}",
null => "no shape",
_ => $"unknown object of type {shape.GetType().Name}"
};
Each arm consists of a pattern, the => token, and an
expression. The arms are separated with commas. The _
discard pattern matches anything and plays the role of the
default label. Because the null case is handled before the
discard, the compiler knows that shape is not null in the
last arm and does not warn about shape.GetType().
$ dotnet run circle with area 12.57 rectangle with area 12 square with area 25 unknown object of type String no shape
Constant and relational patterns
A constant pattern tests for equality with a constant, such as a
number, a character, a string, an enum member, or null. A
relational pattern compares the value with a constant using the
<, >, <=, or
>= operators.
int[] scores = [95, 82, 74, 61, 48, 100, -5];
foreach (var score in scores)
{
Console.WriteLine($"{score,4}: {Grade(score)}");
}
static string Grade(int score) => score switch
{
< 0 or > 100 => "invalid",
100 => "perfect",
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 50 => "D",
_ => "F"
};
We convert test scores to grades.
< 0 or > 100 => "invalid", 100 => "perfect", >= 90 => "A", >= 80 => "B",
The order of the arms matters. The value 100 must be tested before
>= 90; the score 95 does not match the first two arms and
falls to the third one. If we put >= 90 above
100, the compiler reports error CS8510, because the
100 arm could never be reached.
$ dotnet run 95: A 82: B 74: C 61: D 48: F 100: perfect -5: invalid
Logical patterns
Patterns can be combined with the and, or, and
not keywords. Parentheses group patterns where needed. The
and combinator binds more tightly than or.
char[] chars = ['a', 'Z', '7', ' ', '#', '\t', '\u00e9'];
foreach (var c in chars)
{
Console.WriteLine($"{(int)c,3}: {Classify(c)}");
}
string? name = Environment.GetEnvironmentVariable("NO_SUCH_VARIABLE");
if (name is not null)
{
Console.WriteLine($"found {name}");
}
else
{
Console.WriteLine("variable not set");
}
static string Classify(char c) => c switch
{
>= 'a' and <= 'z' or >= 'A' and <= 'Z' => "letter",
>= '0' and <= '9' => "digit",
' ' or '\t' or '\n' => "whitespace",
not (>= ' ' and <= '~') => "control or non-ASCII",
_ => "punctuation"
};
We classify characters, and we check a string for null.
>= 'a' and <= 'z' or >= 'A' and <= 'Z' => "letter",
A character is a letter if it lies in one of two ranges. The expression
reads as (>= 'a' and <= 'z') or (>= 'A' and <= 'Z')
and the value is evaluated only once.
not (>= ' ' and <= '~') => "control or non-ASCII",
The not pattern negates the pattern in parentheses. Characters
outside the printable ASCII range match this arm, for instance the
character é with the code 233.
if (name is not null)
The is not null check is the idiomatic way to test for a
non-null value in modern C#.
$ dotnet run 97: letter 90: letter 55: digit 32: whitespace 35: punctuation 9: whitespace 233: control or non-ASCII variable not set
Property patterns
A property pattern matches the properties or fields of an object against nested patterns. It is written in curly brackets. An object matches only if it is not null and all listed members match.
List<Order> orders =
[
new(new Customer("Paul", "SK"), 120m, false),
new(new Customer("Lucy", "DE"), 45m, false),
new(new Customer("Roger", "SK"), 30m, true),
new(new Customer("Anna", "US"), 600m, false),
];
foreach (var order in orders)
{
Console.WriteLine($"{order.Customer.Name,-6} {order.Total,6} {Shipping(order)}");
}
static string Shipping(Order order) => order switch
{
{ IsExpress: true } => "express courier",
{ Customer.Country: "SK", Total: >= 100 } => "free domestic",
{ Customer.Country: "SK" } => "domestic",
{ Total: > 500 } => "free international",
_ => "international"
};
record Customer(string Name, string Country);
record Order(Customer Customer, decimal Total, bool IsExpress);
We pick a shipping method for orders.
{ IsExpress: true } => "express courier",
{ Customer.Country: "SK", Total: >= 100 } => "free domestic",
The first arm checks a single boolean property. The second arm uses an
extended property pattern: Customer.Country reaches
into a nested object. It is a shorter form of
{ Customer: { Country: "SK" } }. The nested patterns can be any
patterns; here we combine a constant pattern for the country and a
relational pattern for the total.
$ dotnet run Paul 120 free domestic Lucy 45 international Roger 30 express courier Anna 600 free international
Positional patterns
A positional pattern deconstructs a value and matches the parts
against nested patterns. It works with tuples and with any type that has a
Deconstruct method, which includes positional records.
Point[] points = [new(0, 0), new(3, 0), new(0, -2), new(4, 5), new(-1, 6), new(-2, -2), new(7, -3)];
foreach (var p in points)
{
Console.WriteLine($"{p}: {Locate(p)}");
}
static string Locate(Point p) => p switch
{
(0, 0) => "origin",
(_, 0) => "on the x-axis",
(0, _) => "on the y-axis",
( > 0, > 0) => "quadrant I",
( < 0, > 0) => "quadrant II",
( < 0, < 0) => "quadrant III",
_ => "quadrant IV"
};
var tuples = new (int, string)[] { (200, "GET"), (404, "GET"), (201, "POST"), (500, "PUT") };
foreach (var (status, method) in tuples)
{
string msg = (status, method) switch
{
(200, "GET") => "page loaded",
(201, "POST") => "resource created",
( >= 400 and < 500, _) => "client error",
( >= 500, _) => "server error",
_ => "other"
};
Console.WriteLine($"{method} {status}: {msg}");
}
record Point(int X, int Y);
We locate points in the coordinate system and react to combinations of an HTTP status and method.
(0, 0) => "origin", (_, 0) => "on the x-axis", ( > 0, > 0) => "quadrant I",
The Point record is deconstructed into its X and
Y values. The discard _ matches any value in its
position.
string msg = (status, method) switch
{
(200, "GET") => "page loaded",
( >= 400 and < 500, _) => "client error",
We can create a tuple on the fly to switch on several values at once. This
replaces nested if statements.
$ dotnet run
Point { X = 0, Y = 0 }: origin
Point { X = 3, Y = 0 }: on the x-axis
Point { X = 0, Y = -2 }: on the y-axis
Point { X = 4, Y = 5 }: quadrant I
Point { X = -1, Y = 6 }: quadrant II
Point { X = -2, Y = -2 }: quadrant III
Point { X = 7, Y = -3 }: quadrant IV
GET 200: page loaded
GET 404: client error
POST 201: resource created
PUT 500: server error
var pattern and the when guard
The var pattern matches any value, including null, and assigns it
to a new variable. A when clause adds an extra condition to an
arm; the arm is taken only if the pattern matches and the condition is
true.
string[] commands = ["add 3 4", "neg 7", "div 8 0", "div 9 3", "mul 2", "hello"];
foreach (var cmd in commands)
{
Console.WriteLine($"{cmd,-8} -> {Run(cmd)}");
}
static string Run(string cmd) => cmd.Split(' ') switch
{
["add", var a, var b] => $"{int.Parse(a) + int.Parse(b)}",
["neg", var a] => $"{-int.Parse(a)}",
["div", _, "0"] => "division by zero",
["div", var a, var b] when int.Parse(a) % int.Parse(b) == 0 => $"{int.Parse(a) / int.Parse(b)}",
["div", var a, var b] => $"{double.Parse(a) / double.Parse(b):F3}",
[var op, ..] when op is "add" or "mul" or "div" => $"wrong number of arguments for {op}",
_ => "unknown command"
};
We write a tiny command interpreter. Each command is split into words and the resulting array is matched.
["add", var a, var b] => $"{int.Parse(a) + int.Parse(b)}",
The array must have exactly three elements, the first being
"add". The other two are captured with var patterns. This is a
list pattern, explained in the next section.
["div", _, "0"] => "division by zero",
["div", var a, var b] when int.Parse(a) % int.Parse(b) == 0 => $"{int.Parse(a) / int.Parse(b)}",
["div", var a, var b] => $"{double.Parse(a) / double.Parse(b):F3}",
The guard decides between integer and floating-point division. If the guard is false, matching continues with the next arm.
[var op, ..] when op is "add" or "mul" or "div" => $"wrong number of arguments for {op}",
A pattern can also be used inside the guard with the is
expression.
$ dotnet run add 3 4 -> 7 neg 7 -> -7 div 8 0 -> division by zero div 9 3 -> 3 mul 2 -> wrong number of arguments for mul hello -> unknown command
List patterns
List patterns, available since C# 11, match arrays, lists, and
other countable and indexable types element by element. The slice
pattern .. matches zero or more elements and may appear
at most once in a list pattern.
int[][] arrays = [[], [7], [1, 2], [1, 2, 3, 4, 5], [0, 9, 9, 0]];
foreach (var arr in arrays)
{
string desc = arr switch
{
[] => "empty",
[var only] => $"one element: {only}",
[var a, var b] => $"two elements: {a}, {b}",
[0, .., 0] => "starts and ends with zero",
[var first, .. var middle, var end] => $"first {first}, last {end}, {middle.Length} in between"
};
Console.WriteLine($"[{string.Join(", ", arr)}] {desc}");
}
List<string> words = ["sky", "cup", "blue"];
if (words is [_, .. var rest])
{
Console.WriteLine($"rest: {string.Join(' ', rest)}");
}
if (words is [.., { Length: > 3 } last])
{
Console.WriteLine($"last word {last} is long");
}
We describe arrays of different lengths and look at a list of words.
[] => "empty",
[var only] => $"one element: {only}",
[0, .., 0] => "starts and ends with zero",
The empty pattern matches a sequence with no elements. The
[0, .., 0] pattern matches sequences with at least two
elements whose first and last elements are 0.
[var first, .. var middle, var end] => $"first {first}, last {end}, {middle.Length} in between"
A slice can be captured in a variable. For arrays, the slice is a new
array. This last arm makes the switch exhaustive: every
array has zero, one, two, or more elements, so no discard arm is needed.
if (words is [.., { Length: > 3 } last])
The elements of a list pattern are themselves patterns. Here a property pattern checks the length of the last word.
$ dotnet run [] empty [7] one element: 7 [1, 2] two elements: 1, 2 [1, 2, 3, 4, 5] first 1, last 5, 3 in between [0, 9, 9, 0] starts and ends with zero rest: cup blue last word blue is long
Exhaustiveness
The compiler warns when a switch expression does not handle
every possible input. If such an expression gets a value that no arm
matches, it throws a SwitchExpressionException at runtime.
Console.WriteLine(Name(Color.Red));
Console.WriteLine(Name(Color.Blue));
Console.WriteLine(Name((Color)7));
static string Name(Color c) => c switch
{
Color.Red => "red",
Color.Green => "green",
Color.Blue => "blue"
};
enum Color { Red, Green, Blue }
The switch expression handles all three named members of the
Color enum.
Console.WriteLine(Name((Color)7));
An enum variable can hold any value of its underlying type, not just the
named members. The compiler knows this and issues warning CS8524 even
though all named members are covered. Casting 7 to Color
triggers the exception. Adding a discard arm that throws an
ArgumentOutOfRangeException with a clear message is the usual
fix. If a named member were missing, the warning would be CS8509.
$ dotnet build Program.cs(5,34): 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. $ dotnet run red blue Unhandled exception. System.Runtime.CompilerServices.SwitchExpressionException: Non-exhaustive switch expression failed to match its input. Unmatched value was 7. at <PrivateImplementationDetails>.ThrowSwitchExpressionException(Object unmatchedValue) at Program.<<Main>$>g__Name|0_0(Color c) in Program.cs:line 5 at Program.<Main>$(String[] args) in Program.cs:line 3
Source
In this article we have worked with pattern matching in C#. See also the switch expression, deconstruct, record, and check type tutorials.
Author
List all C# tutorials.