rulururu

post Code nested inside a namespace?

April 11th, 2008

Filed under: .NET — Kai @ 7:38 am

Recently I wondered if code should be always nested in a namespace or not.

The question actually shouldn’t be which is “better” rather which is better for a particular case.

using bar;
namespace Foo {
  // etc
}

or

namespace Foo {
  using foo;
  // etc
}

I don’t know how to answer the question “which is better?” because I do not know the intended purpose of the code. I therefore tried to think of ways that these could be different, and answer the question “how do these differ?”

The answer is that if there is only one namespace in the file, it hardly matters. If there are two or more namespaces in the file, then put the directives you want shared amongst them at the top of the file, and the ones you do not want shared inside each the namespace. I further noted that having multiple top-level namespaces in the same file is a little weird, so maybe don’t even go there and make it a moot point.

My first statement was not right. There is a way that these could be different that I forgot about. The first version is equivalent to

using global::bar;
namespace Foo {
  // etc
}

The second version is equivalent to

namespace Foo {
  using global::bar;
  // etc
}

unless Foo contains a namespace called bar. In that case, it is equivalent to

namespace Foo {
  using global::Foo.Blah;
  // etc
}

So there are at least two ways that things can get broken here. First, moving a not-fully-qualified directive from outside to inside (or vice versa) may cause a semantic change in the program. And second, if there is a not-fully-qualified directive inside the namespace which refers to a top-level namespace then adding a child namespace that collides with that name can introduce a semantic change in the program.

Therefore my advice is:

  • have only one top-level namespace per file
  • if you choose to put using directives inside your namespaces then fully qualify them with the global alias qualifier

If you take this advice then it really does not matter whether the directives go inside the namespace or outside; either way you will not accidentally break yourself by introducing a name collision.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)