Reputation: 1288
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.
Upvotes: 0
Views: 299
Reputation: 5194
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:
Placing using-alias directives within the namespace eliminates compiler confusion between conflicting types.
When multiple namespaces are defined within a single file, placing using directives within the namespace elements scopes references and aliases.
Upvotes: 1
Reputation: 106
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
Upvotes: 3
Reputation: 5771
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.
Upvotes: 2