Re: Possible Compiler Bug (C# 3.0)

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



"Tomasz J" <oegweb@xxxxxxxxxxxxx> wrote in message news:egq13zc4IHA.4920@xxxxxxxxxxxxxxxxxxxxxxx
The attached program does not compile. The error message says:
"A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else"
- which does not make much sense. Is it a compiles bug?
TJ

class Program
{
static void Main(string[] args)
{
switch (0) {
case 0:
for (int i = 0; ; ) {
}
case 1:
// error CS0136: A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else
int i = 0;
}
}
}

It's not a bug, it's a documented feature. Contrary to other "flavors" of C, in C# it is not allowed to have a variable in a nested block named the same as a variable in its containing block. For instance, the following would compile in traditional C, but not in C#:

while (condition1)
{
int i;
...
while (condition2)
{
int i;
...
}
}

The reasoning is that this used to lead to many programming errors. If you access "i" in the inner block, it refers to the "i" that is declared inside that same block, but in a larger program it is easy to make a mistake and think that it is referring to the outer "i". To avoid this risk, the C# designers decided to disallow this situation.

.



Relevant Pages