Bug in C# scoping rules?

  • Thread starter Thread starter Amil
  • Start date Start date
A

Amil

Am I missing something there and just being a bonehead or what? When I
compile the code below, the compiler warns "A local variable named 'foo'
cannot be declared in this scope because it would give a different meaning
to 'foo', which is already used in a child scope to denote something else".

I can't have PREVIOUS foo uses in nested scopes? What am I missing here??
I guess the compiler is not smart enough to see that the last foo doesn't
have any nested foo declarations after it. ^%$@!*^&!

static void Main(string[] args)
{
if (true)
{
int foo = 3;
}

if (true)
{
int foo = 57;
}

int foo = 5; // THIS LINE IS FAILING COMPILER "Compiler Error CS0136"
Console.WriteLine(foo);
}
 
Amil said:
Am I missing something there and just being a bonehead or what? When I
compile the code below, the compiler warns "A local variable named 'foo'
cannot be declared in this scope because it would give a different meaning
to 'foo', which is already used in a child scope to denote something else".

I can't have PREVIOUS foo uses in nested scopes? What am I missing here??

From the C# language spec section 15.5.1:

<quote>
The scope of a local variable declared in a local-variable-declaration
is the block in which the declaration occurs.
</quote>

So in other words, the scope of "foo" includes the section of the block
which is *before* the declaration itself.
 
Amil said:
static void Main(string[] args)
{
if (true)
{
int foo = 3;
}

if (true)
{
int foo = 57;
}

int foo = 5; // THIS LINE IS FAILING COMPILER "Compiler Error
CS0136" Console.WriteLine(foo);

Why would you even write such code?
 
Chuck said:
To pose theoretical discussion questions?

I must be missing something. What good is a theory without a practical
application? I see no real world use for the example provided so it
seems to be a very poor framework for discussion.
 
Ok - in practice I agree. Its a poor programming practice to declare the
same variable in multiple places for different uses in the same proceedure.
However, the guy may have been asking simply to gain a better understanding
of scoping in C#.

But man - you need to get some more sunlight or something - I was trying to
make a joke about it. :)
 
Frank Oquendo said:
Why would you even write such code?

To test the meaning of the specification. To get a better understanding of
the rules.

Because the compiler follows rules, rather than saying, "I don't like your
programming style, so I'm not going to compile your progam!"
 
Back
Top