Why can't I declare a variable with the same name that has already been declared, but the new variable is beyond the scope of another variable

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 I cannot declare a variable outside the loop foreach, since the compiler gives an error that the variable is already declared. The scope of the variable foreach(and therefore target) is completed, where I declare this new variable.

+2
source share
2 answers

The scope of a local variable extends right up to the start of the block in which it was declared. Thus, the volume of your second ad is virtually the entire external cycle foreach. From the C # 4 specification, section 3.7:

, (§8.5.1), , .

8.5.1:

, , , . , - . .

, ​​ , , - 8.5.1.

, - , , , .

+9

, foreach, foreach, . ,

{
string target .....
}

, , , . , .

+2

All Articles