Skip to content

Pattern matching C# 7.0code reductionreadabilitycorrectness

Pattern match expressions 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. 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 ​

More information ​

Powered by Intracia