tags:

views:

162

answers:

3

I'm running into an issue where I can't make a reference to a class in a different namespace. I have 2 classes:

namespace Foo
{
    public class Class1 { ... }
}

namespace My.App.Foo
{
    public class Class2
    {
        public void SomeMethod()
        {
            var x = new Foo.Class1; // compile error!
        }
    }
}

The compile error is:

The type or namespace name 'Class1' does not exist in the namespace 'My.App.Foo'

In this situation, I can't seem to get Visual Studio to recognize that "Foo.Class1" refers to the first class. If I mouse-over "Foo", it shows that its trying to resolve that to "My.App.Foo.Class1"

If I put the line:

using Foo;

at the top of the .cs file that contains Class2, then it also resolves that to "My.App.Foo".

Is there some trick to referencing the right "Foo" namespace without just renaming the namespaces so they don't conflict? Both of these namespaces are in the same assembly.

+10  A: 

You can use global:: to globally qualify a namespace: global::Foo.Class1 should work,.

You could also alias global::Foo to make things easier. At the top of your source file, below your using statements, add:

using AliasClass1=global::Foo.Class1;

Now you can use:

AliasClass1 c = new AliasClass1();
// and so on.

Of course, you can use a better name than AliasClass :-)

LBushkin
ding ding ding - cut the man a check.
Sky Sanders
That doesn't work in my environment. I think you need to have global before the ::
BlueMonkMN
@BlueMonkMN - yes I tidied that up just now.
LBushkin
heh, 8 years of C# development experience, and somehow i've never seen "using global::...". That works perfectly. Thanks!
rally25rs
Shame I had the right answer first, but you got all the points ;)
BlueMonkMN
+1  A: 
var x = new global::Foo.Class1();
BlueMonkMN
+1  A: 

In addition to LBushkin's answer, you might be interested in these articles by Eric Lippert :

Do not name a class the same as its namespace, Part One
Do not name a class the same as its namespace, Part Two
Do not name a class the same as its namespace, Part Three
Do not name a class the same as its namespace, Part Four

They are not directly related to your problem, but they give an interesting insight on naming strategies

Thomas Levesque