Saturday, January 30, 2010

When to Define Your Own Namespaces

In the "Hello, World" application, we used the Console.WriteLine method that's defined in the System namespace. In fact, all .NET types and classes are defined in namespaces. However, we didn't create a namespace for our application, so let's address that issue.
Namespaces are a great way of categorizing your types and classes so as to avoid name collisions. Microsoft places all the .NET class and type definitions in specific namespaces because it wants to make sure that its names don't conflict with the names of anyone using its compilers. However, whether you should use namespaces comes down to one question: will the types and classes you create be used in an environment not controlled by you? In other words, if your code is being used only by members of your own team, you can easily create naming rules such that name collision doesn't occur. However, if you're writing classes that will be used by third-party developers, in which case you don't have any control over naming practices, you should definitely use namespaces. In addition, since Microsoft recommends using your company name as the top-level namespace, I would recommend using namespaces anytime someone else might see your code. Call it free advertising.

No comments:

Post a Comment