1. #1
    AceInfinity's Avatar
    Join Date
    Feb 2012
    Location
    Canada
    Posts
    1,725

    C# 7.0 Switch Case (Pattern Matching)

    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.

    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 by AceInfinity; 05-22-2018 at 02:39 PM.
    x BlueRobot and Tekno Venus say thanks for this.
    Automation Programmer
    Microsoft MVP [2012 - 2018]


    • Ad Bot

      advertising
      Beep.

        
       

  2. #2
    Tekno Venus's Avatar
    Join Date
    Jul 2012
    Location
    UK
    Age
    20
    Posts
    5,943
    • specs System Specs
      • Manufacturer:
        Custom Built
      • Motherboard:
        ASUS Z170I ITX
      • CPU:
        Intel Core i7 6700K
      • Memory:
        16GB DDR4
      • Hard Drives:
        500GB Samsung 850 EVO, 2TB Seagate HDD
      • Power Supply:
        450W Corsair SFX
      • Case:
        Silverstone SG13 ITX
      • Cooling:
        Corsair H60i
      • Display:
        Dell U2715H - 2160x1440 27 inch
      • Operating System:
        Windows 10 Pro x64

    Re: C# 7.0 Switch Case (Pattern Matching)

    Ooh, that's quite cool - will have to try that out. Reminds me of using guards in Haskell.
    AceInfinity says thanks for this.


Similar Threads

  1. Can't Switch Users after defragment
    By FeldBalance in forum Windows 8 | Windows RT
    Replies: 0
    Last Post: 01-31-2015, 06:27 PM
  2. Random BSODs with no apparent cause or pattern - Windows 7 x64
    By AIO in forum BSOD, Crashes, Kernel Debugging
    Replies: 14
    Last Post: 06-26-2014, 10:41 PM
  3. BSOD when I switch to ATI 5470
    By mnz in forum BSOD, Crashes, Kernel Debugging
    Replies: 6
    Last Post: 02-10-2014, 08:08 PM
  4. BSOD 124 After Graphics Card Switch
    By ronnocerman in forum BSOD, Crashes, Kernel Debugging
    Replies: 4
    Last Post: 01-29-2014, 05:48 PM

Log in

Log in