Visual Studio “15” Preview 4 was recently released, so I decided to take it for a spin. In the upcoming C# 7.0, of the features being implemented, pattern matching is probably the most interesting. Consider how often we’ve designed code that uses a switch statement with complex cases, but then when we go to implement the design, a nested if-then-else statement must be coded instead because switch labels must be constant expressions. With pattern matching, this will finally change.
In theory, when the feature is fully implemented, we could write complex switch statements such as:
Unfortunately, while this example compiles, it does not run properly yet, in Visual Studio “15” Preview 4.
Years ago, I used to write C code that would contain declaration expressions. This would simultaneously assign a value and test to see if the value was non-zero. You can do this in C++, e.g.,
In C#, we can use patterns to declare local variables within an expression, extending the declaration expression existing in C++:
If the switch is rewritten as a nested if-then-else, the code works fine. Note, the scope of pattern matching variables is within the then clause, not the else clause of the if statement. I’m not sure why this would be the design, as in C/C++, the scope of declaration expression variables extend into the else clause. But perhaps it is to allow reuse of the same variable in a nested if-then-else.
Further Information
https://www.infoq.com/news/2016/04/CSharp-7
Essential .NET – Designing C# 7, Mark Michaelis, December 2015 https://msdn.microsoft.com/en-us/magazine/mt595758.aspx
Pattern Matching for C#Â https://github.com/dotnet/roslyn/blob/future/docs/features/patterns.md
https://github.com/dotnet/roslyn/issues/2136
https://github.com/dotnet/roslyn/issues/206
https://github.com/dotnet/roslyn/blob/future/docs/features/patterns.md
Advanced Pattern Matching Features Removed From C# 7Â https://www.infoq.com/news/2016/05/csharp7-pattern-matching-removed
C# 7 Features Previewed https://www.infoq.com/news/2016/04/CSharp-7
Unification: pattern matching, but twice as nice! By: May 31, 2011  http://www.lshift.net/blog/2011/05/31/unification-pattern-matching-but-twice-as-nice/
onhttps://github.com/dotnet/roslyn/blob/master/docs/Language%20Feature%20Status.md