Search code examples
c#namespaces

C# namespace alias - what's the point?


Where or when would one would use namespace aliasing like

 using someOtherName =  System.Timers.Timer;

It seems to me that it would just add more confusion to understanding the language.


Solution

  • That is a type alias, not a namespace alias; it is useful to disambiguate - for example, against:

    using WinformTimer = System.Windows.Forms.Timer;
    using ThreadingTimer = System.Threading.Timer;
    

    (ps: thanks for the choice of Timer ;-p)

    Otherwise, if you use both System.Windows.Forms.Timer and System.Threading.Timer in the same file, then you'd have to keep giving the full names (since Timer could be confusing).

    It also plays a part with extern aliases for using types with the same fully-qualified type name from different assemblies - rare, but useful to be supported.


    Actually, I can see another use: when you want quick access to a type but don't want to use a regular using because you can't import some conflicting extension methods. A bit convoluted but here's an example:

    namespace RealCode {
        //using Foo; // can't use this - it breaks DoSomething
        using Handy = Foo.Handy;
        using Bar;
        static class Program {
            static void Main() {
                Handy h = new Handy(); // prove available
                string test = "abc";            
                test.DoSomething(); // prove available
            }
        }
    }
    namespace Foo {
        static class TypeOne {
            public static void DoSomething(this string value) { }
        }
        class Handy {}
    }
    namespace Bar {
        static class TypeTwo {
            public static void DoSomething(this string value) { }
        }
    }