static void

C#7 Pattern Matching

Published Sunday 19 February 2017

Pattern matching is new in C#7 / Visual Studio 2017. Remember C#7 isn't the same a .Net version upgrade - you can use these language features in projects targeting .net Core, .net 4.6, 4.5, 4.0 and even 3.5.

Pattern matching is essentially a better syntax to test types.

"is" better

This is the existing (C# 1-6) "is" syntax.

if (o is Person)
{
    var person = (Person) o;
    UpdatePerson(person);
}

You can make a slightly more efficient version with "as"

var person = o as Person;
if (person != null)
{
    UpdatePerson(person);
}

In C#7 the "is" syntax can have a variable name afterwards - so it's a test and assignment in one syntax.

if (o is Person person)
 {
     UpdatePerson(person);
 }

One complication is that the variable "person" has method scope. If you re-use "person" below the closing "if" braces, you'll get the "Use of unassigned local variable" compilation error.

"case" better

More useful is the updated "switch" statement. Previously the "case" tests had to be constants. Now they can be types with assignment.

switch (o)
{
    case Person person:
        UpdatePerson(person);
        break;
    case Cat cat:
        UpdateCat(cat);
        break;
}

Unlike old-style switches, order is important! (Except the "default" case, which is always last, even if you write it first...)

The case test can be extended with a "when" (not "where" like in linq). Now you can do ranges in switch statements.

switch (i)
{
    case 1:
        Console.WriteLine("One");
        break;
    case int j when j > 1:
        Console.WriteLine("More than one");
        break;
}

Note that variable scope is now within the "case" block (unlike "if").

switch (o)
{
    case Person person when person.Name != null:
        UpdateUnknownPerson(person);
        break;
    case Person person:
        UpdatePerson(person);
        break;
}

Previously: Visual Studio 2017 Net Versions (18 February 2017)