Skip to content

Pattern matching C# 7.0code reductionreadabilitycorrectness

Allow expressions to be pattern matched for type and value checking.

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

More information