This is based on an email I send my .NET team at work
Continuing our tour of new features in C#-7, today we come to Pattern Matching.
Pattern matching is a feature of many programming languages that let you test if the contents of a variable meet a certain shape, or pattern. So you can test if a variable is of a class, or in some languages, if a variable has certain properties.
If you’re familiar with the more robust pattern-matching capabilities of a language like F#, you’d be disappointed with what’s being introduced here, but this feature is only going to get more powerful and expressive over time.
There’s two new constructs in C#-7 that support pattern matching.
It’s really common in certain data models and class hierarchies to need to test what particular type you have, cast it, and then work with the casted result. For example, imagine this data model which I’ve extracted from a side project:
Processing these results often involves determining what type of result you have, then casting and accessing its properties.
The new C# pattern matching feature lets you simplify this a little bit. An
expression can also provide a variable name, and if the type matches, the variable
name comes in scope and has the casted value.
A little bit cleaner, right?
The variable declared in the
is expression is in scope following the
expression, but is considered unassigned. Consider:
I like this feature for reducing some of the extra noise that gets in the way of understanding whats going on in a function.
They’ve also added support for pattern matching in switch statements, with the additional ability to filter on properties of the matched pattern.
Once again, ReSharper puts red squiggles under everything, but it does still compile.
is expressions, variables declared in the
case statement are only
in scope for that case. You can’t access
r outside of the switch or in another
I don’t tend to use
switch statements all that often, but its nice that
concepts you can use in
if blocks can also apply in
Here’s the proposal for Pattern Matching on GitHub: https://github.com/dotnet/roslyn/blob/features/patterns/docs/features/patterns.md
There are a number of features of this proposal not yet implemented, that will hopefully come in future versions of C#.