Assembly 1
namespace Foo
{
public class Foo { }
}
Assembly 2
using Foo;
public class Bar
{
Foo foo = new Foo();
}
I discovered today that the above gives error Type name expected but namespace name found.
I find this surprising. As far as I’m aware, you can’t declare a namespace variable, or new() a namespace. Foo is a type, and it’s being used where the parser expects to find a type, so why can the parser not resolve it correctly? What language feature am I overlooking which means that the compiler team were unable to implement this?
Eric Lippert’s blog posts (parts one; two; three; four) give good insight into this. From part one:
Here we’ve only actually got an X, but I think the compiler tries to work out whether that means it’s a namespace or a type before checking whether or not there’s anything else after it.
Personally, I don’t mind this restriction. It means you’re discouraged from writing code with a namespace and class called the same thing – and as that’s a confusing situation from a human point of view, I’m happy for it to be discouraged.