Thursday, November 03, 2005

When is a namespace not a namespace?

I found an interesting thing today when moving some code around in a ASP.NET 1.1 application today. For historical reasons there's a user control that contains another user control (yes I know that's a bad thing). In the process of moving the files around and renaming so that the names actually made sense I managed to name the two controls the same thing, but in different namespaces.

So I have two controls, the latter contained within the former:
  • Site.Group.DistributionGroupDetails.ascx
  • Site.Properties.Details.DistributionGroupDetails.ascx
The application compiles with no build errors but when you try to view the page that contains the Site.Group.DistributionGroupDetails.ascx control what happens? A runtime error complaining that DistributionGroupDetails.ascx is defined twice (or more correctly DistributionGroupDetails_ascx is defined twice). But how can it be as the two user controls are in different namespaces.

As you know under the bonnet the ASCX file inherits from the ASCX.CS and you can put the ASCX.CS in whatever namespace you want. But when it compiles the ASCX file does it care what the namespace of the ASCX.CS file is - does it hell.

It puts it in the ASP namespace and creates a class for the ASCX file that inherits from the ASCX.CS file. So effectively it's created the following two classes:
  • ASP.DistributionGroupDetails : Site.Group.DistributionGroupDetails.ascx
  • ASP.DistributionGroupDetails : Site.Properties.Details.DistributionGroupDetails.ascx
So although the user controls are in different namespaces according to the ASCX.CS file when they're compiled it's magically put them in the same namespace. That's nice of it!

I've not done any more testing than this but it seems pretty stupid for it to ignore the original namespace. I can't be the only person who's done this and then wondered why it's broken?

No comments: