C# switch variable initialization: Why does this code NOT cause a compiler error or a runtime error?
c#, switch-statement
Solution
You have to be careful how you think about the `switch` statement here. There's no creation of variable scopes going on at all, in fact. Don't let the fact that just because the code within cases gets indented that it resides within a child scope.
When a switch block gets compiled, the `case` labels are simply converted into labels, and the appropiate `goto` instruction is executed at the start of the switch statement depending on the switching expression. Indeed, you can manually use `goto` statements to create "fall-through" situations (which C# does directly support), as the MSDN page suggests.
goto case 1;
If you specifically wanted to create scopes for each case within the `switch` block, you could do the following.
...
case 1:
{
string x = "SomeString";
...
break;
}
case 2:
{
string x = "SomeOtherString";
...
break;
}
...
This requires you to redeclare the variable `x` (else you will receive a compiler error). The method of scoping each (or at least some) can be quite useful in certain situations, and you will certainly see it in code from time to time.
Problem
``` ... case 1: string x = "SomeString"; ... break; case 2: x = "SomeOtherString"; ... break; ... ``` Is there something that I am not understanding about the switch statement in C#? Why would this not be an error when case 2 is used? Edit: This code works and doesn't throw an error.