Pattern matching
Type and constant patterns
A pattern is a test of a value together with the names it binds. The oldest one is the type pattern: value is string text asks whether the value is a string and, if it is, gives the name text to it inside the branch.
Console.WriteLine("values:");
object?[] values = { 42, -3, "text", "hi", 2.5, null };
foreach (var value in values)
{
var description = value switch
{
int n when n < 0 => $"negative int {n}",
int n => $"int {n}",
string { Length: > 3 } s => $"long string {s}",
string s => $"short string {s}",
double d => $"double {d}",
null => "null",
_ => "other",
};
Console.WriteLine(description);
}
dotnet run
values:
int 42
negative int -3
long string text
short string hi
double 2.5
null
The array is object?[], so the numbers are boxed and the null is allowed. The arms run in order: the guard on the first arm catches the negative number, the property pattern on the third asks a string for a length above three, and the plain string arm takes the rest. The null arm comes before the discard because the discard matches null too.
A property pattern
A property pattern tests members of the matched value: { Length: > 3 } asks for a value whose Length property is above three. Several properties go in one pattern, and a property may itself be a pattern.
var p = new Point(0, 5);
Console.WriteLine(p is { X: 0, Y: > 0 });
Console.WriteLine(p is { X: 0, Y: 0 });
var line = "hello world";
Console.WriteLine(line is { Length: > 5 } and not "goodbye");
record Point(int X, int Y);
dotnet run
True
False
True
Property patterns work on any type with those properties, including a string and an anonymous type. They are the readable way to ask several questions about one object without a chain of &&, and a switch over them reads as a table of cases.
List patterns
A list pattern matches an array or a span by its elements. The slice .. stands for any number of elements, and a var before it captures them.
Console.WriteLine("patterns:");
int[] numbers = { 1, 2, 3 };
if (numbers is [1, .., 3])
{
Console.WriteLine("starts with 1 and ends with 3");
}
if (numbers is [var first, ..])
{
Console.WriteLine($"first: {first}");
}
Console.WriteLine(numbers is [_, _, _]);
dotnet run
patterns:
starts with 1 and ends with 3
first: 1
True
[1, .., 3] needs at least two elements, the first 1 and the last 3; the middle may be empty. [var first, ..] needs at least one and binds it. [_, _, _] needs exactly three, which is why the last line is true. A list pattern is a length test and an element test in one expression, and it works on an array, a span and a list.
is, and, or and not
The is operator takes any of these patterns, and the combinators are the words and, or and not rather than the symbols of a bool expression:
int value = 7;
Console.WriteLine(value is > 0 and < 10);
Console.WriteLine(value is 0 or 7);
Console.WriteLine(value is not 0);
object boxed = "text";
Console.WriteLine(boxed is string { Length: 4 });
dotnet run
True
True
True
True
is not 0 is not the same as != 0 for every type: the pattern also succeeds for a null, because null is not 0 either. Where that matters, the null arm comes first.
Exercises
- Add a decimal to the array of the first program. Which arm catches it, and why?
- Write a property pattern that accepts a string of at least three characters that does not start with a space.
- Match an empty array and an array of one element with list patterns. How many arms does each need?
- Replace is not 0 with != 0 and call both with a null int. Which one throws?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the type pattern
value is string textdo?Answer
Tests that the value is a string and binds it to text
The pattern checks the type and gives the matched value a name that the branch can use.
-
What does
{ Length: > 3 }ask of a string?Answer
That its Length property is greater than 3
The property pattern tests the named property with a relational pattern, so "text" matches and "hi" does not.
-
What does this program print?
int[] numbers = { 1, 2, 3 }; Console.WriteLine(numbers is [1, .., 3]);Answer
True
The first element is 1, the last is 3, and the slice covers the middle, so the pattern matches.
-
How many elements does
[_, _, _]require?Answer
Exactly three
Each underscore is one element pattern, so the array must have exactly three elements.
-
What does this program print?
int[] numbers = { 1, 2 }; if (numbers is [var first, ..]) { Console.WriteLine(first); }Answer
1
The pattern binds the first element and the branch prints it; outside the branch the name is not definitely assigned.
-
Why must a null arm come before the discard in a switch expression?
Answer
The discard matches null too, so it would take that value first
Arms are tested in order, and _ matches everything, so any arm after it can never run.
-
What does this program print?
object boxed = 42; Console.WriteLine(boxed is int n && n > 40);Answer
True
The type pattern succeeds, binds 42 to n, and the && then tests the bound value.
-
Which pattern combines two comparisons into one test?
Answer
> 0 and < 10
The word and joins two relational patterns; commas separate arms and && is for bool expressions.
-
What does a list pattern work on?
Answer
An array, a span and a list
The pattern needs a length and an indexer, which arrays, spans and List<T> all provide.
-
What does
is not 0accept that!= 0does not?Answer
A null value
The pattern succeeds for any value that is not the constant 0, and null is such a value; != on a nullable throws or is lifted.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev