In my mental model, counter variables defined inside for
become private because it cannot be access from outside as follows.
for (int x = 0; x < 2; x++) ;
//Console.WriteLine(x); x does not exist in the current context
My confusion occurs when I declared the same variable as follows,
for (int x = 0; x < 2; x++) ;
//Console.WriteLine(x); x does not exist in the current context, but why cannot I declare
//int x = 1;
Why does the compiler disallow me to declare a variable with the same name as another inaccessible variable? It does not make sense to me. :-)
To make more confusing compare it with
{
int x = 1;
}
{
int x = 2;
}
which is allowed by the compiler. But both below are not allowed.
static void Foo()
{
int x = 1;
{ int x = 2; }
}
static void Bar()
{
{ int x = 2; }
int x = 3;
}