What's new

C# 7.0 Switch Case (Pattern Matching)

AceInfinity

Moderator, Programming, Contributor
Joined
Feb 21, 2012
Messages
1,729
Location
Canada
A really cool feature that I've been starting to use more frequently is pattern matching which also is cleanly implemented for switch statements in C#.

Example:
Code:
switch (_commTransport)
{
    case TerminalDebugClient _:
        ((TerminalDebugClient)_commTransport).HostValidation += OnHostValidation;
        break;
    case SshDebugClient _:
        ((SshDebugClient)_commTransport).HostValidation += OnHostValidation;
        break;
}
This allows me to check the type of object described by my interface and also assign it to an identifier if I wanted to process it directly, or just use _ to avoid that. :thumbsup2:

I find this a bit more legible than the if ( is ...) variation when it comes to multiple statements, and definitely more so than the as operator and null check.
 
Last edited:

Tekno Venus

Senior Administrator, Site Designer
Staff member
Joined
Jul 21, 2012
Messages
6,068
Location
UK
Ooh, that's quite cool - will have to try that out. Reminds me of using guards in Haskell.
 

AceInfinity

Moderator, Programming, Contributor
Joined
Feb 21, 2012
Messages
1,729
Location
Canada
Apparently C# 8.0 comes out with recursive patterns and expressions now for switch statements. :eek: Not quite sure how this will translate to the C# language in practice though just like the idea of Tuples. Seems like a very rare case, especially if you want to promote code readability. I see some of these as more "functional-style" language features.
 
Top