Search code examples
c#switch-statementfall-through

Falling through switch statement (works sometimes?)


I have a switch statement such as the one below:

switch (condition)
{
    case 0:
    case 1:
        // Do Something
        break;
    case 2:
        // Do Something
    case 3:
        // Do Something
        break;
}

I get a compile error telling me that Control cannot fall through from one case label ('case 2:') to another

Well... Yes you can. Because you are doing it from case 0: through to case 1:.

And in fact if I remove my case 2: and it's associated task, the code compiles and will fall through from case 0: into case1:.

So what is happening here and how can I get my case statements to fall through AND execute some intermediate code?


Solution

  • There is a difference between stacking labels and fall-through.

    C# supports the former:

    case 0:
    case 1:
        break;
    

    but not fall-through:

    case 2:
        // Do Something
    case 3:
        // Do Something
        break;
    

    If you want fall-through, you need to be explicit:

    case 2:
        // Do Something
        goto case 3;
    case 3:
        // Do Something
        break;
    

    The reasoning is apparent, implicit fall-through can lead to unclean code, especially if you have more than one or two lines, and it isn't clear how the control flows anymore. By forcing the explicit fall-through, you can easily follow the flow.

    Reference: msdn