I tried with "case: 2 || 5" ,but it didn't work. The purpose is to not write same code for different values.
8,627 1 1 gold badge 42 42 silver badges 47 47 bronze badges asked May 11, 2009 at 14:49 Ivan Prodanov Ivan Prodanov 35.4k 79 79 gold badges 178 178 silver badges 250 250 bronze badges What do you mean "it didn't work"? Does it give you syntax errors, or logical errors? Commented May 28, 2013 at 20:03 Starting with C# 9, this exact syntax is allowed. Commented Jun 23, 2021 at 11:30By stacking each switch case, you achieve the OR condition.
switch(myvar)answered May 11, 2009 at 14:51 Jose Basilio Jose Basilio 51.3k 13 13 gold badges 122 122 silver badges 117 117 bronze badges
Joel, it doesn't support fall through but it DOES support stacking (e.g., an empty case 2 in this answer executes the case 5 section).
Commented May 11, 2009 at 14:54 This was exactly what I was looking for. Good job, your work is appreciated. Commented Apr 27, 2017 at 13:22switch(myvar)answered May 11, 2009 at 14:51 David Webb David Webb 193k 57 57 gold badges 316 316 silver badges 302 302 bronze badges
switch(myvar) < case 2 or 5: // . break; case 7 or 12: // . break; // . >
answered Nov 11, 2020 at 20:21
466 5 5 silver badges 11 11 bronze badges
This is more readable then allowing it fall through, downside it's C# 9.0 up only as you pointed out.
Commented Nov 9, 2021 at 12:27case 2: case 5: do something break;
answered May 11, 2009 at 14:51
4,436 2 2 gold badges 24 24 silver badges 31 31 bronze badges
Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write
switch(myvar) < case 2: case 5: < //your code break; >
answered May 11, 2009 at 14:55
3,186 6 6 gold badges 35 35 silver badges 39 39 bronze badges
Note that this is only true for empty cases. Cases with actual body do not automatically fall through.
Commented May 11, 2009 at 14:58Since C# 8 there are switch expressions that are better readable: no case , : and break; / return needed anymore. Combined with C# 9's logical patterns:
static string GetCalendarSeason(DateTime date) => date.Month switch < 3 or 4 or 5 =>"spring", 6 or 7 or 8 => "summer", 9 or 10 or 11 => "autumn", 12 or 1 or 2 => "winter", _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: ."), >;
Limitation: with this syntax, at the right of the => you cannot use curly braces ( < and >) for statements.