C# 7.0 New Features Series [ Pattern matching ]

Pattern matching

Currently in C# 7.0 two of the existing language constructs are being enhanced with patterns:

  • is expressions can now have a pattern on the right hand side, instead of just a type
  • case clauses in switch statements can now match on patterns, not just constant values


Is-Expressions with Patterns

Prior to C# 7.0 it was not possible to match is expressions for constant values. They were needed primitive types to match the value against. In C# 7.0 now it is possible to match the is expression for constant values directly.


Next improvement in the is expression by pattern matching is done by Type pattern of form T of x where T is the type and x is the variable of that type. Imagine you have a variable of type object and it contains an integer value in it. If you have to perform any mathematics with that variable you will have to first match it if it is an integer through is expression and then you will have to cast that variable of type object to another variable of type integer so that you can perform any mathematics on that.

But in C# 7.0 it is easily done without any unnecessary type casting.


With the help of Type Pattern Is expression can also be used in conjunction with Try methods to parse different types.


Switch statements with patterns

Switch statement is now generalized so that:

  • You can switch on any type (not just primitive types)
  • Patterns can be used in case clauses
  • Case clauses can have additional conditions on them

Here’s a simple example:

  • The order of case clauses now matters: Just like catch clauses, the case clauses are no longer necessarily disjoint, and the first one that matches gets picked. It’s therefore important that the square case comes before the rectangle case above. Also, just like with catch clauses, the compiler will help you by flagging obvious cases that can never be reached. Before this you couldn’t ever tell the order of evaluation, so this is not a breaking change of behavior.
  • The default clause is always evaluated last: Even though the null case above comes last, it will be checked before the default clause is picked. This is for compatibility with existing switch semantics. However, good practice would usually have you put the default clause at the end.
  • The null clause at the end is not unreachable: This is because type patterns follow the example of the current is expression and do not match null. This ensures that null values aren’t accidentally snapped up by whichever type pattern happens to come first; you have to be more explicit about how to handle them (or leave them for the default clause).

Pattern variables introduced by a case label are in scope only in the corresponding switch section.

Further Reference: 

What’s New in C# 7.0

  • Show Comments (0)

Your email address will not be published. Required fields are marked *

comment *

  • name *

  • email *

  • website *