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?
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 acase
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 adefault
label.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With