C# scopes — am I missing something here?

Last time I checked, the scope of a variable drew the line after which it ceased to exist. For instance, in Java, when you defined a variable in a for loop, the minute the loop was over the variable ceased to exist:

for(int i = 0; i < N; i ++) {

int j = 0;

// do stuff with j

}

// j should cease to exist after here

I hoped that scopes would be the same in C# (with the language being very similar to Java) however in this situation the compiler whinges to death:

foreach(int i in some_array) {

int j = 10;

// do stuff here
}

// after here j should be no more yet …

int j = 20;

And that’s where the compiler goes Whoa, hang on a minute, I just saw and int j right above this other one… and it goes poop.

In the C# scope specs you can read:

The scope of a local variable declared in a for-initializer of a for statement (Section 8.8.3) is the for-initializer, the for-condition, the for-iterator, and the contained statement of the for statement.

I’m assuming here that a foreach statement qualifies as a for statement, so I definitely don’t understand what’s going on here.

What’s even more interesting, although reasonable, is that if we sorround the new definition of j with curly brackets, therefore creating a new scope, we make the compiler happy.

Oh well …

Post a Comment

Your email is never published nor shared. Required fields are marked *