Namespace collision

Programming comments edit

Today I came across an interesting namespace collision. I’m writing a library to wrap a 3rd party API. So without getting into specifics I’ll try to illustrate the situation on a sample piece of code. Let’s say we have a class called Test in TestNamespace namespace.

namespace TestNamespace
{
    public class Test
    {
        public static void StaticMethod()
        {
        }
    }
}

and the calling class is something like this:

namespace DifferentNamespace.TestNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            TestNamespace.Test.StaticMethod();
        }
     }
}

This code doesn’t compile because compiler thinks “TestNamespace.Test” is actually “DifferentNamespace.TestNamespace.Test”.

Adding a using directive doesn’t help either. As it has the same namespace as the subnamespace of the calling class it always resolves to calling class’s namespace. The solution is using “global” namespace.

namespace DifferentNamespace.TestNamespace
{
    using TestNamespace = global::TestNamespace;

    class Program
    {
        static void Main(string[] args)
        {
            TestNamespace.Test.StaticMethod();
        }
    }
}

By explicitly specifying which TestNamespace we are referring to we resolve the conflict. One thing to keep in mind is that we have to define it inside the namespace. If we used it outside the DifferentNamespace.TestNamespace, then inside the namespace TestNamespace would still mean “DifferentNamespace.TestNamespace”

Before this incident, I never had to use the global keyword. Probably the best way to avoid this is by naming conventions but sometimes you may not be able to change the namespace name. You can break lots of things if there are dependant parties on that code. So every now and then this tip may come in handy, just like it did to me in this instance.

Comments