why is this illegal

  • Thread starter Thread starter Andy Fish
  • Start date Start date
A

Andy Fish

this fragment of c# does not compile:

{
{
string s = "a";
}
string s = "a";
}

It says that the 2 declarations conflict. AFAIK the scope of a variable
declaration is from the point in the source file it is declared until the
end of the enclosing block. By this definition they don't conflict

Andy
 
Isn't it true? For example:

static void myMethod()
{
for(int iCount = 0; iCOunt <= 100; iCount++)
{
Console.WriteLine("Value of iCount: " + iCount.ToString());
}

// fails because iCount is declared in the for loop, and the variable
falls out of scope
// after the for loop ends...
Console.WriteLine("Value of iCount: " + iCount.ToString());
}
 
James Curran said:
Technically, they do not conflict. However, 99.9% of the time, when you
have something like that, it's a mistake, and you accidentally refer to "s"
thinking you're getting the other one.

C++ lets you shot yourself inthe foot that way. C# does not.

No, they *do* conflict according to the spec.

From section 10.7 of the spec:

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

It's the whole block, not "from the point of declaration onwards".
 
why it's illegal?
if ypu want to know how's the rule:
The scope of a local variable declared in a local-variable-declaration is
the block in which the declaration occurs.
But:
It is an error to refer to a local variable in a textual position that
precedes the local-variable-declarator of the local variable.

if you want to know why c# does this?
See posting of James Curran
 
Back
Top