0

Is it possible in C# to execute a switch case without breaking?

This is an example of a switch where using break in desired

var bar = "Foo";
switch (foo) {
    case 0:
    case 1:
        bar += " Bar";
    case 2:
    case 3:
        Console.WriteLine(bar);
        break;
    default:
        break;
}

This is what the code should produce:

0: Foo Bar
1: Foo Bar
2: Bar
3: Bar
Else: nothing

Is it possible to do this or would I have to do:

var bar = "Foo";
if(foo == 0 || foo == 1) bar += " Bar";
switch (foo) {
    case 0:
    case 1:
    case 2:
    case 3:
        Console.WriteLine(bar);
        break;
    default:
        break;
}
nick zoum
  • 7,216
  • 7
  • 36
  • 80

2 Answers2

4

This is called implicit fall through which is not supported in C#.

You can use goto case statement though.

var bar = "Foo";
switch (foo) {
    case 0:
    case 1:
        bar += " Bar";
        goto case 2;
    case 2:
    case 3:
        Console.WriteLine(bar);
        break;
    default:
        break;
}
Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
0

You can simplify your code, if switch case is not mandatory in your code. You can try something like this:

var bar = "Foo";
if(foo == 0 || foo == 1) bar += " Bar";
if(foo >= 0 && foo <= 3) //Replacement of switch with single if condition
    Console.WriteLine(bar);

Output:
if foo == 1 then print -> "Foo Bar"
if foo == 3 then print -> "Foo"
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44