Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# error when class shares name with namespace

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?

like image 941
fearofawhackplanet Avatar asked Dec 13 '11 13:12

fearofawhackplanet


1 Answers

Eric Lippert's blog posts (parts one; two; three; four) give good insight into this. From part one:

This reveals an interesting point about the design of the “type binding” algorithm in C#. That is, the algorithm which determines what type or namespace a name like “X.Y” is talking about. We do not “backtrack”. We do not say “well, suppose X means this. Then Y would have no meaning. Let’s backtrack; suppose X means this other thing, oh, yes, then Y has a meaning.” We figure out what X unambiguously means, and only then do we figure out what Y means. If X is ambiguous, we don’t check all the possibilities to see if any of them has a Y, we just give up.

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.

like image 128
Jon Skeet Avatar answered Oct 22 '22 08:10

Jon Skeet