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

后端 未结 6 1381
粉色の甜心
粉色の甜心 2020-12-17 23:46
...
case 1:
   string x = \"SomeString\";
   ...
   break;
case 2:
   x = \"SomeOtherString\";
   ...
   break;
...


Is there something that

6条回答
  •  醉话见心
    2020-12-18 00:24

    There is no compiler error because the switch statement does not create a new scope for variables.

    If you declare a variable inside of a switch, the variable is in the same scope as the code block surrounding the switch. To change this behavior, you would need to add {}:

    ...
    case 1:
        // Start a new variable scope 
        {
            string x = "SomeString";
            ...
        }
        break;
    case 2:
        {
            x = "SomeOtherString";
            ...
        }
        break;
    ...
    

    This will cause the compiler to complain. However, switch, on it's own, doesn't internally do this, so there is no error in your code.

提交回复
热议问题