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;
}
That's because a
switchstatement is scoped across cases. Therefore, when theswitchstatement is originally processed it defines a variable namedsomethingand would have its default value ... in this casenull.And to be more precise, when the IL is generated, a variable is available in scope for any
caseat or below its definition. So, if a variable is declared in the secondcaseit's not available in the firstcasebut would be available in the thirdcase.