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.
{
var person = (Person) o;
UpdatePerson(person);
}
You can make a slightly more efficient version with "as"
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.
{
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.
{
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.
{
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").
{
case Person person when person.Name != null:
UpdateUnknownPerson(person);
break;
case Person person:
UpdatePerson(person);
break;
}