This is based on an email I send my .NET team at work
Happy Friday,
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.
Is-Expressions
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:
1 | public class HttpResult |
Processing these results often involves determining what type of result you have, then casting and accessing its properties.
1 | public void Process(HttpResult result) |
The new C# pattern matching feature lets you simplify this a little bit. An is
expression can also provide a variable name, and if the type matches, the variable
name comes in scope and has the casted value.
1 | public void Process(HttpResult result) |
A little bit cleaner, right?
The variable declared in the is
expression is in scope following the is
expression, but is considered unassigned. Consider:
1 | object o = 5; // stick an int into an object reference |
I like this feature for reducing some of the extra noise that gets in the way of understanding whats going on in a function.
Pattern Matching in Switch Statements
They’ve also added support for pattern matching in switch statements, with the additional ability to filter on properties of the matched pattern.
1 | public void ProcessWithSwitch(HttpResult result) |
Once again, ReSharper puts red squiggles under everything, but it does still compile.
Unlike the 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
case block.
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 switch
es.
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#.