简体   繁体   中英

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?

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();
        }
    }
}

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();
        }
    }
}

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM