On Sunday, 21 February 2021 at 21:03:27 UTC, Jack wrote:
Why doesn't this compiles?
class Baa
{
Foo Foo = new Foo();
}
Local variables inside functions are a little bit special because
everything happens in sequence. This is a declaration, where
there is a new namespace, but order doesn't matter.
So in the function:
void foo() {
// there is no local variable Foo yet until after this line,
// so there is no ambiguity - only existing Foo here is the
class outside
Foo Foo = new Foo();
// Foo now refers to the local variable
// same as if you did
x++; // error: x doesn't exist yet
int x; // only AFTER this point does x exist
}
But in the class:
class foo {
// the names in here are all created simultaneously
// and thus the local Foo is considered existing as it
// looks up the name Foo
Foo Foo = new Foo();
// same as if you did
int y = x; // error is "Variable x not readable at compile
time", NOT "no such variable" because all declarations flash into
existence simultaneously
int x; // this line and the above could be swapped without
changing anything
}
So the local variable isn't special just because of the
namespace, it is also special because order matters inside
functions but not outside.