SHARE:

Introducing C# 9: Improved pattern matching

Introduction

Pattern matching has been introduced in C# 6 and has well evolved since. The latest improvement was pretty interesting on C# 8 which has been released last year. If you missed pattern matching improvements on C# 8 , here is a nice article from Miguel Bernard (@MiguelBernard88): https://blog.miguelbernard.com/pattern-matching-in-csharp/. If you have missed all new features in C# 8, you can read also his great serie here: https://blog.miguelbernard.com/csharp-8-0-new-features/.

In this article I will show you all the great new features of pattern matching.

Relational patterns

C# 9 allows you to use relational pattern which enables the use of <, >, <= and >= in patterns like this:

Logical patterns

C# 9 lets you use logical operators like ‘and’, ‘or’ and ‘not’ , they can even be combined with relational patterns like this:

Not patterns

‘not‘ logical operator can also be used in a if statement (it works also with a ternary statement), like this:

Simple type pattern

Another nice improvement of C# 9: Simple type pattern. When a type matches, the underscore symbol _ (commonly named discard parameter) can be omitted, thats makes the syntax lighter:

Hope you like this bunch of improvements 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: