C# foreach variable scope

This question already has an answer here:

  • Why can't a duplicate variable name be declared in a nested local scope? 9 answers

  • Why isn't the first gridView variable only accessible in the foreach loop scope ?

    It is, but the compiler (language definition) simply forbids overlapping scopes.

    A simplified version that yields the same error:

    {   // outer block, scope for the second `i`
    
        for(int i = 0; i < 10; i++)  // nested 'i', the first we see
        {
           // scope of first `i`  
        }
    
        int i = 3;  // declaration of a second `i`, not allowed
    }
    

    The reason this is hard to read an get is that the second 'i' may only be used after its declaration, but its scope is the entire outer block.

    See C# Language specification, § 3.7: Scopes


    The articles you mention to have read are irrelevant here, as you do not have a closure over the loop variable.

    What happens is that you have a variable of the same name in the enclosing scope. This is not allowed (at least for scopes starting in methods). You have the same problem if you'd try declaring gridView in a for loop or just a nested block.

    You can have two loops next to each other using the same variable name, though, since they don't overlap. Note also that variable scope is determined by blocks, even though you can access them only after they have been declared. That means that even though your foreach loop is before you declare the second gridView variable, their scopes do overlap.

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

    上一篇: 在Laravel视图中使用foreach变量

    下一篇: C#foreach变量作用域