Why can't I use the same variable as an inner loop does?
Q: Why can't I do the following:
namespace Bug
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
for(int i=0; i<100; i++)
{
}
int i = 0;
}
}
}
the compiler gives me an error on the “int i = 0;” part of the code.
A: This is correct behavior, and is covered in section 3.7 of the language spec. It says, “The scope of a local variable declared in a local-variable-declaration (8.5.1) is the block in the which the declaration occurs”.
The scope of i is therefore the entire Main() function, and that means that the use in the for loop is a re=use, and therefore is not allowed.
This behavior is inteded to make incorrect re-use of variable names (such as in a cut and paste) less likely.
[Author: Eric Gunnerson]