Why I cannot declare the variable with same name that already declared but new variable is out of the scope of other variable

独自空忆成欢 提交于 2019-12-13 12:40:14

问题


private void Abc()
{
    string first="";
    ArrayList result = new ArrayList();
    ArrayList secResult = new ArrayList();
    foreach (string second in result)
    {
        if (first != null)
        {
            foreach (string third in secResult)
            {
                string target;
            }
        }

        string target;//Here I cannot decalre it. And if I don't declare it and
        //want to use it then also I cannot use it. And if it is in if condition like
        //the code commented below, then there is no any complier error.
        //if (first != null)
        //{
        //    string target;
        //}
    }
}

I cannot understand: Why can't I declare the variable outside the foreach loop, as compiler gives an error that the variable is already declared. The scope of the foreach (and hence the target variable) is over where I am declaring this new variable.


回答1:


The scope of a local variable extends all the way up to the start of the block in which it's declared. So the scope of your second declaration as actually the whole of the outer foreach loop. From the C# 4 spec, section 3.7:

The scope of a local variable declared in a local-variable-declaration (§8.5.1) is the block in which the declaration occurs.

and in section 8.5.1:

The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.

So even though the second variable hasn't been declared at the point where the first variable occurs, it's still in scope - so the two declarations between them violate 8.5.1.

The language was designed this way to prevent errors - it would be odd if simply moving the location of a local variable declaration within the block in which it's declared and before its first use changed the validity of the code.




回答2:


That is because the second declaration is for the entire scope of the method scope of the first foreach loop which includes the second foreach loop contained in the method. so what you need is to restrict the scope of the other string using braces

{
string target .....
}

Well this shouldn't be really required and seems like a sign of code smell, maybe you need to encapsulate the logic into separate methods. i would request you to review the code again and see if it could be reconstructed.



来源:https://stackoverflow.com/questions/9663114/why-i-cannot-declare-the-variable-with-same-name-that-already-declared-but-new-v

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!