Search code examples
c#switch-statementvariable-initialization

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


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;
}

Solution

  • 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.