Getting to know about pattern matching
Pattern matching is a new notion introduced in C# 7.0, which adds some power to the existing operators and statements. You can perform pattern matching on any data type and from that statement you can extract the value of that data type. There are two different types of pattern matching in C# 7.0:
- The Is expression with pattern matching
- Switch statements with pattern matching
The Is expression with pattern matching
In this type of pattern matching, it introduces a new pattern variable out of the expression, allowing you to extract the value of the type. It is similar to the out
variable, but with a limited scope to the surroundings.
Let's look at an example. In the old method, we need to check for the data type, and then we must convert the variable to the specified data type to get the value out of it. Here, if the person
is of type Employee
, we can type cast it to Employee
to get the values of the employee object:
if (person is Employee) { ...