OdeToCode IC Logo

Namespaces and ASP.NET 2.0

Wednesday, February 8, 2006

I've seen grumbling lately over the lack of namespaces in ASP.NET 2.0 projects.

With Visual Studio 2003, if I add a page with the name of WebFormA to a folder with the name of FolderA, inside a project (named ProjectA), then the IDE starts off with a code-behind file that looks like the following.

namespace ProjectA.FolderA
/// <summary>
   /// Summary description for WebFormA.
   /// </summary>
   public class WebFormA : System.Web.UI.Page

The same steps with web project model in Visual Studio 2005 produces the following.

public partial class FolderA_WebFormA : System.Web.UI.Page

Some people believe having a class declared outside of a namespace is an unthinkable tragedy. My question is why?

One reason to use a namespace is to avoid type name collisions. By appending folder names to the front of the class, ASP.NET is avoiding name collisions (although I do wonder when someone will bump up against the max identifier length).

A second reason for using a namespace is to present a logical, organized hierarchy for consumers of the types. Who is the consumer of a WebForm? Typically only the ASP.NET runtime, which doesn’t need a namespace to help it map an HTTP request to an HttpHandler.

Types in a code-beside file are well hidden. The compilation model for ASP.NET 2.0 may even put each type in a separate assembly. In the scenarios where a Page, UserControl, or MasterPage code-beside type is needed outside of it’s own definition, the @ PreviousPage, @ MasterType, and @ Reference directives are needed. Pretending that these types are anonymous isn’t a bad idea. Using a base class or an interface will reduce the tight coupling that occurs when user control and master page types are used by other areas of an application.

If you still need to put Page derived types in a namespace, you'll want to consider using the Web Application Project type, which works like the 1.1 model.