Use of Namespaces in C#

As far as I know, they are used for two things:

• To structure the project into meaningful pieces

• To distinguish classes with the same name

That’s basically it. I would add to your first point that namespaces provide structure larger than just that of the project, since namespaces may span projects and assemblies. I would add to your second point that the primary purpose of namespaces is to add structure to libraries so that it becomes easier to find stuff you need and avoid stuff you do not need. That is, namespaces are there as a convenience for the user of a library, not for the convenience of its creators.

A secondary purpose is to disambiguate name collisions. Name collisions are in practice quite rare. (If the primary purpose of namespaces was to disambiguate collisions then one imagines there would be a lot fewer namespaces in the base class libraries!)

Are there any other things to consider when using namespaces?

Yes. There are numerous aspects to correct usage of namespaces. For example:

  • violating standard naming conventions can cause confusion. In particular, do not name a class the same as its namespace! (See link below for details.)
  • using a namespace can bring extension methods into play that you didn’t expect; be careful
  • where precisely the “using” directive goes can subtly change resolution rules in a world where there are name collisions; these situations are rare, but confusing when they arise
  • collisions often arise in contexts where machine-generated code is interacting with human-generated code; be careful in such situations, particularly if you are the one writing the code generator. Be very defensive; you don’t know what crazy name collisions the person writing the human-generated half is going to create.

See my articles on this subject for more details:

http://blogs.msdn.com/b/ericlippert/archive/tags/namespaces/

And see also the Framework Design Guidelines for more thoughts on correct and incorrect conventions for namespace usage.

Do they have an impact on performance or something like that?

Almost never. Namespaces are a fiction of the C# language; the underlying type system does not have “namespaces”. When you say

using System;
...
class MyException : Exception 
...

there is no class named “Exception”. The class name is “System.Exception” — the name has a period in it. The CLR, reflection, and the C# language all conspire to make you believe that the class is named “Exception” and it is in the namespace “System”, but really there is no such beast as a namespace once you get behind the scenes. It’s just a convention that you can sometimes omit the “System.” from the name “System.Exception”.

Leave a Comment