Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# multiple switch cases same value lambda syntax

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);
like image 448
Itamar Shuval Avatar asked Sep 19 '25 22:09

Itamar Shuval


2 Answers

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.

like image 195
TheGeneral Avatar answered Sep 22 '25 11:09

TheGeneral


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"
};
like image 33
Pavel Anikhouski Avatar answered Sep 22 '25 10:09

Pavel Anikhouski