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

前端 未结 12 1406
长情又很酷
长情又很酷 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条回答
  •  梦毁少年i
    2020-11-21 22:56

    There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier using statements and has to be fully qualified.

    Consider:

    namespace MyNamespace
    {
        using System;
        using MyAlias = System.DateTime;
    
        class MyClass
        {
        }
    }
    

    versus:

    using System;
    
    namespace MyNamespace
    {
        using MyAlias = DateTime;
    
        class MyClass
        {
        }
    }
    

    This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):

    using MyAlias = Tuple>, Expression>>;
    

    With using statements inside the namespace, it suddenly becomes:

    using MyAlias = System.Tuple>, System.Linq.Expressions.Expression>>;
    

    Not pretty.

提交回复
热议问题