Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the control is going from one switch case to another without break c#?

Just started C# and I came to know you cannot go from one switch case to another if there is at least one statement. Error : Control cannot fall through from one case to another .

Just for fun stuff I tried this out :

        char c = 'a';
        switch (c)
        {
            case 'a':
                Console.WriteLine("yes");
                goto JumpToNextCase;
            case 'b':
                 JumpToNextCase:
                Console.WriteLine("Kiddin me?");
                break;

        }

And this worked ! How can it be?Am I now not violating the rule of jumping from one case to other? Any satisfying answer?

like image 727
joey rohan Avatar asked Nov 30 '22 01:11

joey rohan


1 Answers

Yeah, the limitation is just to prevent something that in 99% of cases is an accident and a bug.

However, you don't even need a label to make it work, if you think you want it to work. You can use goto to jump to different case!

char c = 'a';
switch (c)
{
    case 'a':
        Console.WriteLine("yes");
        goto case 'b';
    case 'b':
        Console.WriteLine("Kiddin me?");
        break;
}

You can also jump to default. C# spec mentions that:

8.9.3 The goto statement The goto statement transfers control to a statement that is marked by a label.

goto-statement:
goto   identifier   ;
goto   case   constant-expression   ;
goto   default   ;

(...)

The target of a goto case statement is the statement list in the immediately enclosing switch statement (§8.7.2), which contains a case label with the given constant value.

(...)

The target of a goto default statement is the statement list in the immediately enclosing switch statement (§8.7.2), which contains a default label.

like image 163
MarcinJuraszek Avatar answered Dec 17 '22 03:12

MarcinJuraszek