C# extern aliases

January 21st, 2007

Few days ago I had a chance to know what "namespace conflict" feel like. This should never happen because good programmer doesn't code anything this way but if it does, there is a solution. For example, we have one class in the first assembly:

C#:
  1. namespace Foo
  2. {
  3.     public class Bar
  4.     {                 
  5.         public void Something()
  6.         {
  7.             // do something here
  8.         }
  9.     }
  10. }

and a class in the second assembly:

C#:
  1. namespace Foo
  2. {
  3.     public class Bar
  4.     {                 
  5.         public void Something()
  6.         {
  7.             // do something else here
  8.         }
  9.     }
  10. }

When you try to compile code that use Foo.Bar.Something () you will get an error about ambiguity. Fortunately, with the release of C# 2.0 comes the facility to handle multiple namespace hierarchies, implemented through the extern keyword and compile time configuration.

To use this interesting feature you must follow two steps:

Declare the hierarchies in your code using the extern alias keyword. For example:

C#:
  1. extern alias BlahBlah;
  2. extern alias OhMyGod;
  3. // and usual stuff
  4. using System;
  5. using System.IO;
  6. // ...

Remember that extern alias declarations must not be preceded by anything else.

Final step is to pass special option to the compiler:

csc /r:BlahBlah=assembly1.dll /r:OhMyGod=assembly2.dll someother.cs

Now we have two hierarchies that can be accessed uniquely

C#:
  1. extern alias BlahBlah;
  2. extern alias OhMyGod;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.Collections;
  7. namespace Test
  8. {
  9.     class App
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             BlahBlah::Foo.Bar a = new BlahBlah::Foo.Bar();
  14.             OhMyGod::Foo.Bar b = new OhMyGod::Foo.Bar();
  15.         }
  16.     }
  17. }

It works nice but there is one bad thing about it. You cannot use it with ASP.NET compiler because it simply doesn't support a construction like this. That's a pity :(

Leave a Reply

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!

Powered by Rootnode