Sparrow
Sparrow

Reputation: 88

Differentiating class and namespace when class and namespace have the same name

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            A.B var = new A.B();
        }
    }
}

Compiled with msvc 2019 and .net core 3.1, this code sample gives the following error:

Error   CS0426  The type name 'B' does not exist in the type 'A'

I understand that it's better not to give the same names for classes and namespace. But is there any way to workaround such collision?

Upvotes: 1

Views: 558

Answers (3)

StepUp
StepUp

Reputation: 38164

There is no need to declare namespace as class B is already declared with the same namespace with class A. So just delete A and Visual Studio will figure out what it is desirable:

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            B var = new B();
        }
    }
}

UPDATE:

An alternative solution is:

using _a = A;

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            _a.B var = new _a.B();
        }
    }
}

Upvotes: 5

Sefe
Sefe

Reputation: 14007

You should avoid a scenario where you name your classes and namespaces the same. If you can't or using third party code, you can always refer to the namespace with the global:: keyword:

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            global::A.B var = new global::A.B();
        }
    }
}

Upvotes: 5

Thomas Cook
Thomas Cook

Reputation: 4853

I think you are misunderstanding how namespaces work. You don't need to fully qualify B inside class A. You can simply refer to class B because both classes are in the same namespace. Like so:

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            B var = new B();
        }
    }
}

Upvotes: 2

Related Questions