C# and, or, not pattern matching

Posted by Joe Enos on June 12, 2021 · 1 min read

Pattern matching in C# gives you the ability to shorten some of your code that checks for types, discrete values, and relational comparisons. One way this helps is to replace some of your boolean expressions with the and, or, and not syntax.

if (i is >= 2 and <= 7) { WriteLine("between 2 and 7"); }
if (i is 1 or 2 or 3) { WriteLine("In 1, 2, 3"); }

There's a lot more you can do with pattern matching, so if you haven't looked into them yet, look up some documentation and articles, and see if there are ways it can help you be more productive.

View code on GitHub