C# 8.0 switch - how to handle multiple values as we do with older versions of

Shivanand Patil 1 Reputation point
2021-10-22T12:51:50.953+00:00

In C# 8.0 switch enhancements, how do we perform below matches with new version?

int age = 20;
switch (age)
{
case 10:
case 20:
return "U";
default: return "A";
}
with new switch syntax in C# 8.0 how to handle above one?

var info = age switch {
10 => "U",
20 => "U",
_ => "A"
}

Is there any better way to handle multiple values?

Developer technologies C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-10-22T13:11:07.457+00:00

    Try this syntax too:

    var info = age switch
    {
        10 or 20 => "U",
        _ => "A"
    };
    
    1 person found this answer helpful.

  2. Castorix31 90,521 Reputation points
    2021-10-22T13:32:02.76+00:00

    In C# 8, you can do :

                var info = age switch
                {
                    var n when n == 10 || n == 20 => "U",
                    _ => "A"
                };
    

    (or in C# 9 instead of when)


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.