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.

Pavel
  • 1,278
  • 2
  • 17
  • 34

4 Answers4

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

Tyrant
  • 106
  • 2
  • 3
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.

Georg
  • 5,626
  • 1
  • 23
  • 44
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.

NDJ
  • 5,189
  • 1
  • 18
  • 27
0

Using is always on the top of the document.

Dieter B
  • 1,142
  • 11
  • 20