Why do fall through Switch cases compile in c#

1.9k views Asked by At

As we all know switch cases in c# do not allow you to fall through according the MSDN

Execution of the statement list in the selected switch section begins with the first statement and proceeds through the statement list, typically until a jump statement, such as a break, goto case, return, or throw, is reached. At that point, control is transferred outside the switch statement or to another case label.

Unlike C++, C# does not allow execution to continue from one switch section to the next. The following code causes an error.

If thats the case why does this compile:

void Main()
{
    int  s = 3;
    switch (s)
    {
        case 1:
        case 2:
        case 3:
            Console.WriteLine("hit 3");
            break;
    }
}

Shouldn't this be identified as a compile time error?

1

There are 1 answers

1
mellamokb On BEST ANSWER

First off, the code you provided doesn't throw a run time error. Secondly, it falls under a different category (from same MSDN article, emphasis mine):

A switch statement can include any number of switch sections, and each section can have one or more case labels (as shown in the string case labels example below). However, no two case labels may contain the same constant value.

The difference is whether you have multiple empty case statements, that's allowed. But you can't have a case with code in it, and let it fall through.