Relational, logical and list patterns

1 min read

These build on the basic patternsPattern matchingTest the shape of a value and pull data out of it in one step.Opens in a new tab.

Relational patterns (C# 9.0+)

Relational patterns use relational operators like <, >, <= and >=.

C#
if (value is >= 0 and <= 100) Console.WriteLine("Value is in range 0-100");

Logical patterns (C# 9.0+)

Logical patterns combine patterns using and, or and not.

C#
if (input is (not null and not "")) Console.WriteLine("Input is valid");

List patterns (C# 11.0+)

List patterns match against the elements of a list or array. They can match specific elements, the length, or use a “slice” pattern (..) for the remaining elements.

The first pattern, on line 2, matches a start of 1 and 2 and captures the rest, so it prints Rest: 3,4. The second, on line 3, matches an array with 4 elements whose third element is 3.

C#
int[] numbers = { 1, 2, 3, 4 };if (numbers is [1, 2, .. var rest]) Console.WriteLine($"Starts with 1, 2. Rest: {string.Join(',', rest)}"); // Rest: 3,4if (numbers is [_, _, 3, _]) Console.WriteLine("Third element is 3 and has 4 elements");

Sources