19

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",  
}; 
Theraot
  • 31,890
  • 5
  • 57
  • 86
alekoo73
  • 779
  • 2
  • 10
  • 18

2 Answers2

20

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)),
    };
donatasj87
  • 760
  • 9
  • 23
6

This is based on @donatasj87's answer, so credit to them mainly, but I just thought I'd suggest a slightly different way of writing it.

List<int> oneToThree = new List<int>() { 1, 2, 3 };

int GetValue(int val) => val switch
{
    _ when oneToThree.Contains(val) => DoSomeStuff(),
    _ when val == 4 || val == 5 || val == 6 => DoSomeDifferentSwitch(),
    _ => DefaultSwitch()
};

_ when can be considered as meaning "else when", while _ means just "else".

This way you don't have have the redefinition of val first as i and then as j, which I feel takes a little longer to work out what it's doing.

Note that the new version that @donatasj87 mentioned is now available if you're using C# 9.

jsabrooke
  • 405
  • 7
  • 12
  • 1
    So basically you can preceed any case with `_ when ` to make it work with multiple conditions, I didn't know that, I can't upvote you enough, this is precisely what I've been looking for. – rvnlord Aug 02 '20 at 13:58