Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can this variable in a switch statement be used seemingly without being declared? [duplicate]

Possible Duplicate:
C# switch variable initialization: Why does this code NOT cause a compiler error or a runtime error?

In this switch statement (which to my surprise compiles and executes without error), the variable something is not declared in case 2, and case 1 never executes. How is this valid? How can the variable something be used without being declared?

switch(2){
 case 1:
  string something = "whatever";
  break;
 case 2:
  something = "where??";
  break;
}
like image 950
Travis J Avatar asked May 11 '26 05:05

Travis J


1 Answers

That's because a switch statement is scoped across cases. Therefore, when the switch statement is originally processed it defines a variable named something and would have its default value ... in this case null.

And to be more precise, when the IL is generated, a variable is available in scope for any case at or below its definition. So, if a variable is declared in the second case it's not available in the first case but would be available in the third case.

like image 62
Mike Perrenoud Avatar answered May 13 '26 18:05

Mike Perrenoud