3

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 scope of the loop?

3

1 Answer 1

5

While you can only refer to the outer foo after you declared it, locals are allocated at the beginning of a function which means the inner foo will overshadow the outer one, even if it hasn't been declared yet.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.