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#:
namespace Foo
{
    public class Bar
    {                 
        public void Something()
        {
            // do something here
        }
    }
}

and a class in the second assembly:

C#:
namespace Foo
{
    public class Bar
    {                 
        public void Something()
        {
            // do something else here
        }
    }
}

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#:
extern alias BlahBlah;
extern alias OhMyGod;
// and usual stuff
using System;
using System.IO;
// ...

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#:
extern alias BlahBlah;
extern alias OhMyGod;
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace Test
{
    class App
    {
        static void Main(string[] args)
        {
            BlahBlah::Foo.Bar a = new BlahBlah::Foo.Bar();
            OhMyGod::Foo.Bar b = new OhMyGod::Foo.Bar();
        }
    }
}

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!