for (int i = 0; i < 10; i++)
{
Foo();
}
int i = 10; // error, \'i\' already exists
----------------------------------------
for (int i = 0; i < 10; i
From the C# spec on local variable declarations:
The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs.
Now, of course, you can't use i before it is declared, but the i declaration's scope is the entire block that contains it:
{
// scope starts here
for (int i = 0; i < 10; i++)
{
Foo();
}
int i = 10;
}
The for i variable is in a child scope, hence the collision of variable names.
If we rearrange the position of the declaration, the collision becomes clearer:
{
int i = 10;
// collision with i
for (int i = 0; i < 10; i++)
{
Foo();
}
}