I’ll show examples of using the pattern matching operators – ‘not’, ‘and’, ‘or‘ – with the is operator. These are nice syntax sugar that make conditional logic a bit easier to read. Note: ‘not’, ‘and’, ‘or’ were added in C# 9.
Table of Contents
‘not’ operator
Here’s an example of the not operator:
if (bird is not Cardinal)
{
Console.WriteLine("Bird is not a Cardinal");
}
Code language: C# (cs)
This is checking if the bird object is not of type ‘Cardinal’. 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 easier to read.
‘and’ operator
You can use the and operator to check if multiple conditions are met. For example, this code checks if a number is between 0 and 10:
if (number is >= 0 and <= 10)
{
Console.WriteLine("Number is between 0-10 inclusive");
}
Code language: C# (cs)
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’ operator
You can use the or operator to check if at least one condition is met. Here’s an example of checking if a number is equal to 0 or 5:
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 easier to read compared to the equivalent code using == and ||:
if (number == 0 || number == 5)
{
Console.WriteLine("Number is 0 or 5");
}
Code language: C# (cs)