Prior to this feature a common situation was to use is
to check the type of an object and then to cast it to that type so it could be used as that type. This was mostly prevalent in if
and switch
statements.
C# 7.0's pattern matching allows you to perform this test using a more expressive syntax and to use the casted value of the object if it matches the pattern.
Code
C#
if (myExpression is LambdaExpression lambda) {
return lambda.Body;
}
C#
if (myExpression is LambdaExpression) {
var lambda = (LambdaExpression)myExpression;
return lambda.Body;
}
Notes
- Generic type pattern matching C# 7.1 adds matching of generic types.
- Recursive pattern matching C# 8.0 adds matching of nested patterns.
- Switch property pattern matching C# 8.0 adds matching of properties in switch statements.
- Switch tuple pattern matching C# 8.0 adds matching of tuples in switch statements.
- Type pattern improvements C# 9.0 adds
not
,and
, andor
as well as constant comparison operations. - Extended property patterns C# 10.0 adds matching of properties using regular
.
dot notation.