Pattern matching
Pattern matching is the process of checking whether a value has a particular shape as well as extracting information out of the value when the matching is successful. To some extent, that is what we regularly do with the if
and switch
statements when we check whether an object has some value and then proceed to extract information from it. However, this is a rudimentary form of pattern matching.
In C# 7, new capabilities are added to is
and switch
statements to enable pattern matching capabilities that drive a better separation of data and code and lead to more concise and readable code. The pattern matching capabilities are extended with new features in C# 8. You will learn about these in Chapter 15, New Features of C# 8.
The is expression
At runtime, the is
operator checks that an object is compatible with a given type (the general form, expr is type
). However, in C# 7, this was extended to include several forms of pattern matching:
- Type pattern...