Why does a local variable inside a foreach loop conflict with a variable declared outside the loop?

Given this code:

List<string> things = new List<string>();

foreach (string thing in things)
{
    string foo = thing.ToUpper();
}

string foo = String.Empty;

      

Why does the compiler complain that foo is declared twice? Surely the instance declared in the foreach loop is only valid within the loop?

+3


source to share


1 answer


While you can only refer to the outer one foo

after you have declared it, the locales are allocated at the beginning of the function, which means that the inner one foo

will overshadow the outer one, even if it hasn't been declared yet.



+5


source







All Articles