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",
};
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)),
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With