C# classics: what's the difference of putting your using clauses inside or outside your namespace?
Posted: (EET/GMT+2)
In C#, using directives can be placed either outside the namespace or inside
it. Both compile, but the scope is slightly different.
Let's see the classic example first. The following code snippet places the using directive outside the namespace. You've seen this thousands of times:
using System.Text;
namespace DemoApp
{
public class TestClass
{
}
}
As you are likely aware, you can also place the using statement inside the namespace:
namespace DemoApp
{
using System.Text;
public class TestClass
{
}
}
The practical difference is in scope. Let me explain.
When the using directive is outside the namespace, it applies to the entire
file. When it is inside the namespace, it only applies within that namespace block.
This becomes more visible when multiple namespaces exist in the same file:
using System.Text;
namespace FirstNamespace
{
public class FirstClass
{
StringBuilder builder = new StringBuilder();
}
}
namespace SecondNamespace
{
public class SecondClass
{
StringBuilder builder = new StringBuilder();
}
}
Both namespaces can access StringBuilder because the
using directive is file-scoped.
But with namespace-local imports:
namespace FirstNamespace
{
using System.Text;
public class FirstClass
{
StringBuilder builder = new StringBuilder();
}
}
namespace SecondNamespace
{
public class SecondClass
{
// StringBuilder would require full qualification here
}
}
Now the import only affects FirstNamespace. Since it's somewhat unusual for a file to have multiple namespaces, customary C# code usually places using directives outside the namespace for simplicity and consistency.
Another reason this matters is name resolution. Namespace-local imports participate slightly differently in aliasing and conflict resolution, although this is uncommon in normal business applications.
Since C# 10 (corresponding to .NET 6 in 2021), the topic became slightly less visible because global using directives were introduced:
global using System.Text;
These imports apply to the entire project instead of a single file.
In practice, the inside/outside placement rarely affects application behavior directly, but understanding the scope rules can help when dealing with larger legacy codebases or resolving namespace conflicts.
Hope this helps!