C# 7.0 Switch Case (Pattern Matching)

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
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:
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.
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top