Variable declaration in a C# switch statement

Why is it that in a C# switch statement, for a variable used in multiple cases, you only declare it in the first case?

For example, the following throws the error "A local variable named 'variable' is already defined in this scope".

switch (Type)
{
    case Type.A:
            string variable = "x";
                break;
    case Type.B:
            string variable = "y";
                break;
}

However, per the logic, the initial declaration should not be hit if the type is Type.B . Do all variables within a switch statement exist in a single scope, and are they created/allocated before any logic is processed?


I believe it has to do with the overall scope of the variable, it is a block level scope that is defined at the switch level.

Personally if you are setting a value to something inside a switch in your example for it to really be of any benefit, you would want to declare it outside the switch anyway.


如果您想要将变量作用于某个特定的案例,只需将案例放在自己的块中即可:

switch (Type)
{
    case Type.A:
    {
        string variable = "x";
        /* Do other stuff with variable */
    }
    break;

    case Type.B:
    {
        string variable = "y";
        /* Do other stuff with variable */
    }
    break;
}

Yes, the scope is the entire switch block - unfortunately, IMO. You can always add braces within a single case, however, to create a smaller scope. As for whether they're created/allocated - the stack frame has enough space for all the local variables in a method (leaving aside the complexities of captured variables). It's not like that space is allocated during the method's execution.

链接地址: http://www.djcxy.com/p/2426.html

上一篇: 为什么我不能打开一个字符串?

下一篇: C#switch语句中的变量声明