Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple cases in c# 8.0 switch expressions [duplicate]

In traditional C# switch we have a construction where we can aggregate multiple cases. How can it be done in new c# 8.0 switch expressions?

Switch statement with multiple cases:

    switch (value)
    {
       case 1:
       case 2:
       case 3:
          //do some stuff
          break;
       case 4:
       case 5:
       case 6:
          //do some different stuff
          break;
       default:
           //default stuff
          break;
    }

Example of C# 8 switch expressions:

var result = value switch  
{  
    1 => "Case 1",  
    2 => "Case 2",  
    3 => "Case 3",  
    4 => "Case 4",  
}; 
like image 595
alekoo73 Avatar asked Apr 04 '19 07:04

alekoo73


1 Answers

It should be implemented in more cleaner way in my opinion, but the way I am doing it is like this:

private int GetValue(int val) =>
    val switch
    {
        int i when new [] {1, 2, 3}.Contains(i) => DoSomeStuff(),
        int j when (j == 6 || j == 5 || j == 4) => DoSomeDifferentSwitch(),
        _ => DefaultSwitch()
    };

EDIT: This is planned for C# 9:

colorBand switch
    {
        Rainbow.Red or Rainbow.Orange => new RGBColor(0xFF, 0x7F, 0x00),
        _ => throw new ArgumentException(message: "invalid enum value", paramName: nameof(colorBand)),
    };
like image 125
donatasj87 Avatar answered Sep 21 '22 17:09

donatasj87