Why can’t I use the same variablename e.g. index in a method?
Why can’t the compiler see the different, when I clearly can?
Example:
private void Foo()
{
for (int index = 0; index < 10; index++) // "first"-index
{
// I'm in no doubt, use "first"-index here
// (and only within the scope of the for loop)
}
int index = 0; // "second"-index
// I'm in no doubt, use "second"-index here
// (and below)
}
Is it because the allocation is made at compile time? But then, why can’t the compiler, under the hood, just call the “first”-index for index_1 and the “second”-index for index_2?
If I have
private void Foo()
{
for (int index = 0; index < 10; index++)
{
}
// the runtime don't know index here
}
If the runtime don’t know about index below the for-loop, why can’t we have another variable with that name?
The declaration space of those variables overlaps even if the the scope doesn’t. Check Eric Lippert’s blog on that topic:
Simple names are not so simple
What’s The Difference, Part Two: Scope vs Declaration Space vs Lifetime
The declaration space of a variable is larger that its scope in order to prevent those misleading situations.