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

前端 未结 12 1371
长情又很酷
长情又很酷 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 23:03

    As Jeppe Stig Nielsen said, this thread already has great answers, but I thought this rather obvious subtlety was worth mentioning too.

    using directives specified inside namespaces can make for shorter code since they don't need to be fully qualified as when they're specified on the outside.

    The following example works because the types Foo and Bar are both in the same global namespace, Outer.

    Presume the code file Foo.cs:

    namespace Outer.Inner
    {
        class Foo { }
    }
    

    And Bar.cs:

    namespace Outer
    {
        using Outer.Inner;
    
        class Bar
        {
            public Foo foo;
        }
    }
    

    That may omit the outer namespace in the using directive, for short:

    namespace Outer
    {
        using Inner;
    
        class Bar
        {
            public Foo foo;
        }
    }
    

提交回复
热议问题