C# 9 – Pattern matching operators: is not, and, or

In C# 9 they added several new pattern matching operators that can be combined with the is operator. This is nice syntax sugar that makes conditional logic easier to read.

In this article I’ll show practical examples of using the new operators – is not, and, or.

not pattern: is not A

Here’s an example of the not pattern:

if (bird is not Cardinal) { Console.WriteLine("Bird is not a Cardinal"); }
Code language: C# (cs)

This is equivalent to the following logic that uses the ! operator:

if (!(bird is Cardinal)) { Console.WriteLine("Bird is not a Cardinal"); }
Code language: C# (cs)

I don’t know about you, but I find the is not operator much easier to understand at first glance.

and pattern: is A and B

The following example checks if a number is between two numbers. This is an example of the and pattern and the relational pattern:

if (number is >= 0 and <= 10) { Console.WriteLine("Number is between 0-10 inclusive"); }
Code language: C# (cs)

The and/or operators can be combined with >= and <= operators.

This is equivalent to the following code:

if (number >= 0 && number <= 10) { Console.WriteLine("Number is between 0-10 inclusive"); }
Code language: C# (cs)

This one isn’t a great improvement in readability compared to the other improvements. Hopefully they eventually add an is between pattern operator to make this even more readable.

or pattern: is A or B

Here’s an example of the or pattern:

if (number is 0 or 5) { Console.WriteLine("Number is 0 or 5"); }
Code language: C# (cs)

Notice how the conditional reads exactly the same as the English description?

This is equivalent to the following:

if (number == 0 || number == 5) { Console.WriteLine("Number is 0 or 5"); }
Code language: C# (cs)

Leave a Comment