1
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?

Sparrow
  • 88
  • 7

3 Answers3

5

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();
        }
    }
}
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • 1
    This works in this example, because they happen to live in the same namespace, but personally think @Sefe answer can be more broadly applied. – Michal Ciechan Jan 15 '20 at 11:59
  • @MichalCiechan yeah, it is great solution. I've upvoted. In addition, I've updated my reply by adding an alternative way. – StepUp Jan 15 '20 at 12:04
5

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();
        }
    }
}
Sefe
  • 13,731
  • 5
  • 42
  • 55
2

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();
        }
    }
}
canton7
  • 37,633
  • 3
  • 64
  • 77
Thomas Cook
  • 4,371
  • 2
  • 25
  • 42