In a switch
, if we write any word or single letter instead of default
it does not throw an error.
e.g.
switch(10)
{
case 1:
break;
hello:
break;
}
It runs without throwing an error.
Can anyone explain how this works?
It is compiling because hello:
is a label and thus can be the destination of a goto
. When I compiled this I got warnings about an unreferenced label (since I did not have a goto)
Here is an example you could throw in LINQPad - you will notice that it prints both "1" and "hello":
switch(1)
{
case 1:
"1".Dump();
goto hello;
break;
hello:
"hello".Dump();
break;
}
It's unrelated to the switch
statement. It's a label identifier for the (rarely-used due to being bad practice) goto
statement.
goto something2;
something1:
Console.WriteLine("world");
goto done;
something2:
Console.WriteLine("hello");
goto something1;
done:
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