Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two declarations?

Given this declaration:

using System;
using System.Collections;
using System.Collections.Generic;

namespace AProject.Helpers
{
    public static class AClass
    {

and this declaration

namespace AProject.Helpers
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    public static class AClass
    {

are there any difference in any sense between them? Or is just a difference in coding styles?

I allways used to declared my classes like the first, but recently noticed that Microsoft uses the second.

like image 295
eKek0 Avatar asked Jun 05 '09 06:06

eKek0


1 Answers

In the latter version the using directives only apply within the namespace declaration.

In most cases you'll only have a single namespace declaration:

// Using directives
...
namespace X
{
    // Maybe more using directives
    // Code
}
// End of file

The main difference is if you have multiple namespaces in the same file:

// Using directives
...
namespace X
{
    // Maybe more using directives
    // Code
}

namespace Y
{
    // Maybe more using directives
    // Code
}
// End of file

In this case the using directives in the namespace X declaration don't affect the code inside the namespace Y declaration, and vice versa.

However, that's not the only difference - there's a subtle case which Eric Lippert points out where it can affect the code even with just a single namespace declaration. (Basically if you write using Foo; inside the namespace X declaration, and there's a namespace X.Foo as well as Foo, the behaviour changes. This can be remedied using a namespace alias, e.g. using global::Foo; if you really want.)

Personally I'd stick to:

  • One namespace declaration per file (and usually one top-level type per file)
  • Using directives outside the namespace declaration
like image 192
Jon Skeet Avatar answered Oct 13 '22 09:10

Jon Skeet