It is possible to convert this:
int x = 1;
string xString;
switch (x)
{
case 1:
xString = "1";
break;
case 2:
xString = "2";
break;
default:
xString = "default";
break;
}
Console.WriteLine(xString);
into this:
int x = 1;
string xString = x switch
{
1 => "1",
2 => "2",
_ => "default",
};
Console.WriteLine(xString);
But what would be the syntax to set xString's value to the same value with multiple cases without creating a lambda line for each case?
int x = 1;
string xString;
switch (x)
{
case 1:
xString = "1";
break;
case 2:
case 4:
xString = "even numbers";
break;
default:
xString = "default";
break;
}
Console.WriteLine(xString);
You can't use ranges unfortunately, but you can use when
.
str = i switch
{
int n when (n >= 100) => "asd1",
int n when (n < 100 && n >= 50) => "asd2",
int n when (n < 50) => "asd3",
_ => str
};
or with discards, and implicit referencing
str = i switch
{
_ when i >= 100 => "asd1",
_ when i < 100 && i >= 50 => "asd2",
_ when i < 50 => "asd3",
_ => str
};
switch (C# reference)
Starting with C# 7.0, because case statements need not be mutually exclusive, you can add a when clause to specify an additional condition that must be satisfied for the case statement to evaluate to true. The when clause can be any expression that returns a Boolean value.
You can use when
clause with switch statement here as well
switch (x)
{
case 1:
xString = "1";
break;
case var _ when x % 2 == 0:
xString = "even numbers";
break;
default:
xString = "default";
break;
}
With C# 8 switch
expression and discards it may be simpler
var xString = x switch
{
1 => "1",
_ when x % 2 == 0 => "even numbers",
_ => "default"
};
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