I get the following error in Visual Studio 2008:
Error 1 A local variable named \'i\' cannot be declared in this scope because it would give a different meaning
Yea. Syntactically: The new scope is inside the block defined by the curly strings. Functionally: There are cases in which you may want to check the final value of the loop variable (for example, if you break).
The incrementor does not exist after the for loop.
for (int i = 0; i < 10; i++) { }
int b = i; // this complains i doesn't exist
int i = 0; // this complains i would change a child scope version because the for's {} is a child scope of current scope
The reason you can't redeclare i after the for loop is because in the IL it would actually declare it before the for loop, because declarations occur at the top of the scope.
Just some background information: The sequence doesn't come into it. There's just the idea of scopes - the method scope and then the for
loop's scope. As such 'once the loop terminates' isn't accurate.
You're posting therefore reads the same as this:
int i = 0; // scope error
string str = ""; // no scope error
for (int i = 0; i < 3; i++)
{
string str = "";
}
I find that thinking about it like this makes the answers 'fit' in my mental model better..
I think you're all confusing C++ and C#.
In C++, it used to be that the scope of a variable declared in a for expression was external to the block that followed it. This was changed, some time ago, so that the scope of a variable declared in a for expression was internal to the block that followed it. C# follows this later approach. But neither has anything to do with this.
What's going on here is that C# doesn't allow one scope to hide a variable with the same name in an outer scope.
So, in C++, this used to be illegal. Now it's legal.
for (int i; ; )
{
}
for (int i; ; )
{
}
And the same thing is legal in C#. There are three scopes, the outer in which 'i' is not defined, and two child scopes each of which declares its own 'i'.
But what you are doing is this:
int i;
for (int i; ; )
{
}
Here, there are two scopes. An outer which declares an 'i', and an inner which also declares an 'i'. This is legal in C++ - the outer 'i' is hidden - but it's illegal in C#, regardless of whether the inner scope is a for loop, a while loop, or whatever.
Try this:
int i;
while (true)
{
int i;
}
It's the same problem. C# does not allow variables with the same name in nested scopes.