3

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;
}
Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • Okay, when you output 'something', what does the console tell you? Actually 'where'? Regarding the 'why this works': I can only wager, that when you create a variable in the 'same block' (like the switch statement), it creates the variable, no matter if the actual code is ever reached or not. – ATaylor Oct 11 '12 at 15:58
  • @ATaylor - No, `something`'s scope is limited to the `switch`. – Travis J Oct 11 '12 at 15:59
  • 2
    See the accepted answer of this question: [http://stackoverflow.com/questions/864153/c-sharp-switch-variable-initialization-why-does-this-code-not-cause-a-compiler][1] [1]: http://stackoverflow.com/questions/864153/c-sharp-switch-variable-initialization-why-does-this-code-not-cause-a-compiler – kevin_fitz Oct 11 '12 at 15:59
  • "How can something be used without being initialized?" Note that *that* is not what's happening here. You might read it as using an *undeclared* variable (although that is *also* not the case), but nowhere are you using an unitiliazed variable, that is a separate concept. Indeed, the only usages are assignments. – Anthony Pegram Oct 11 '12 at 16:02
  • @AnthonyPegram - You contradict yourself in those last 2 sentences. An assignment is a use. However, your point about initialization versus declaration is valid and I edited to reflect that. – Travis J Oct 11 '12 at 16:13

1 Answers1

5

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.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232