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. It works with is expressions and with case labels in switch statements, which can also add a when condition.
Code
csharp
if (myExpression is LambdaExpression lambda)
{
return lambda.Body;
}
switch (shape)
{
case Circle c:
return Math.PI * c.Radius * c.Radius;
case Rectangle r when r.Width == r.Height:
return r.Width * r.Width;
case Rectangle r:
return r.Width * r.Height;
}csharp
if (myExpression is LambdaExpression)
{
var lambda = (LambdaExpression)myExpression;
return lambda.Body;
}
var circle = shape as Circle;
if (circle != null)
return Math.PI * circle.Radius * circle.Radius;
var rectangle = shape as Rectangle;
if (rectangle != null)
{
if (rectangle.Width == rectangle.Height)
return rectangle.Width * rectangle.Width;
return rectangle.Width * rectangle.Height;
}Notes
- C# 7.0 supports type patterns (
is Circle c), constant patterns (is null,case 0:) andvarpatterns - Generic type pattern matching C# 7.1 adds matching of generic types.
- Recursive pattern matching C# 8.0 adds matching of nested patterns.
- Switch expressions C# 8.0 allow patterns in an expression form of
switch. - Switch property pattern matching C# 8.0 adds matching of properties.
- Switch tuple pattern matching C# 8.0 adds matching of tuples.
- Type pattern improvements C# 9.0 adds
not,and, andoras well as relational patterns such as> 0. - Extended property patterns C# 10.0 adds matching of properties using regular
.dot notation. - List patterns C# 11.0 adds matching of arrays and lists.