Should 'using' directives be inside or outside the namespace?

前端 未结 12 1374
长情又很酷
长情又很酷 2020-11-21 22:41

I have been running StyleCop over some C# code, and it keeps reporting that my using directives should be inside the namespace.

Is there a technical rea

12条回答
  •  礼貌的吻别
    2020-11-21 22:58

    Another subtlety that I don't believe has been covered by the other answers is for when you have a class and namespace with the same name.

    When you have the import inside the namespace then it will find the class. If the import is outside the namespace then the import will be ignored and the class and namespace have to be fully qualified.

    //file1.cs
    namespace Foo
    {
        class Foo
        {
        }
    }
    
    //file2.cs
    namespace ConsoleApp3
    {
        using Foo;
        class Program
        {
            static void Main(string[] args)
            {
                //This will allow you to use the class
                Foo test = new Foo();
            }
        }
    }
    
    //file2.cs
    using Foo; //Unused and redundant    
    namespace Bar
    {
        class Bar
        {
            Bar()
            {
                Foo.Foo test = new Foo.Foo();
                Foo test = new Foo(); //will give you an error that a namespace is being used like a class.
            }
        }
    }
    

提交回复
热议问题