Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting using statement inside the namespace fails

Tags:

namespaces

c#

I was trying to get some of the old code properly styled with stylecop. It asks for putting the using statements inside. It worked well for all but one. I have reduced the problem to the below code.

namespace B.C
{
    using System;

    public class Hidden
    {
        public void SayHello()
        {
            Console.WriteLine("Hello");
        }
    }
}

namespace A.B.C
{
    using B.C;

    public class Program
    {
        static void Main(string[] args)
        {
            new Hidden().SayHello();
        }
    }
}

this gives compilation error Error

"The type or namespace name 'Hidden' could not be found (are you missing a using directive or an assembly reference?)".

If I move using B.C; above the namespace A.B.C then it builds properly. The class Hidden is developed by different team and we cannot modify it.

like image 297
Tanmoy Avatar asked Sep 28 '12 10:09

Tanmoy


People also ask

Should using be inside or outside namespace?

You cannot have a using directive inside a class as you indicate. It must be on a namespace level, for example outside the outermost namespace , or just inside the innermost namespace (but not inside a class/interface/etc.).

What are namespaces in C#?

The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types.

Can we create alias of a namespace?

Namespace Alias Qualifier(::) makes the use of alias name in place of longer namespace and it provides a way to avoid ambiguous definitions of the classes. It is always positioned between two identifiers. The qualifier looks like two colons(::) with an alias name and the class name. It can be global.

What is using static c#?

With its release in 2015, C# 6 introduced the using static directive. This directive allows us to reference static members without needing to reference the namespace or even the type itself. using static directives can also be used to reference nested types.


1 Answers

As you are inside the namespace A, then B.C will actually be A.B.C.

Use global:: to specify that you are looking from the root:

using global::B.C;
like image 140
Guffa Avatar answered Sep 28 '22 04:09

Guffa