0

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.

4

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

Comments

0

Using is always on the top of the document.

2 Comments

Why's that? The other way it compiles, too?
@Devcon this is not a requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.