简体   繁体   中英

Using and namespace

Where to place using System or other namespaces? Which is the correct or the better way to write code and why? According to my c# trainer it is the second, but everywhere I see the first one.

using System;
namespace Program
{
    class SomeClass
    {
    }
}

or

namespace Program
{
using System;

    class SomeClass
    {
    }
}

According to my c# trainer it is the second, but everywhere I see the first one.

The scope of a using directive is limited to the file in which it appears.

Create a using alias to make it easier to qualify an identifier to a namespace or type. The right side of a using alias directive must always be a fully-qualified type regardless of the using directives that come before it.

Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.

Refer: http://msdn.microsoft.com/en-us/library/sf0df423.aspx

It is your choice. The second can be handy if you have a code file with multiple namespaces, but only want to use a namespace import within one of these namespaces. However, most coding guidelines that I have seen so far specify that a file may only contain one namespace at most and the usings at the top of the file, in alphabetic order.

Stylecop by default requires you to put usings inside namespaces - see here ; for the following reason: (from linked page):

There are subtle differences between placing using directives within a namespace element, rather than outside of the namespace, including:

  1. Placing using-alias directives within the namespace eliminates compiler confusion between conflicting types.

  2. When multiple namespaces are defined within a single file, placing using directives within the namespace elements scopes references and aliases.

使用始终位于文档的顶部。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM