C# – How to identify a namespace without using a string literal

cinversion-of-controlnamespace

My team has a lot of IOC conventions that look something like…

if (type.Namespace == "My.Fun.Namespace")
{
    // do stuff
}

Of course, maintaining this kind of thing becomes brutal after awhile, and we would rather not. The only option I could think of was to store these all in one place, as string constants or something of that nature, but that isn't a lot better… We have been considering making classes that basically serve as namespace identifiers in order to have almost an anchor type to key off of, like, say…

if (type.Namespace == typeof(My.Fun.Namespace.MarkerClass).Namespace)
{
    // do stuff
}

But that just feels weird. So is there another way to solve this one that we just don't know about? If not, has anyone had any luck with the whole marker class concept?

Best Answer

I think your second approach is the best solution. However, I understand that it looks weired to access the namespace by using another class as a reference. Maybe you can maintain a single file with many namespaces only containing a single interface.

namespace My.Fun.NameSpace
{
    interface IContract { }
}
namespace My.Other.NameSpace
{
    interface IContract { }
}

usage:

if (type.Namespace == typeof(My.Fun.Namespace.IContract).Namespace)
{
    // do stuff
}

Another option I could think of is an extension method

namespace System
{
    public static class TypeExtension
    {
        public static bool IsFromFunNameSpace(this Type type)
        {
             return IsFromNameSpace(type, typeof(My.Fun.NameSpace.IContract));
        }

        public static bool IsFromOtherNameSpace(this Type type)
        {
            return IsFromNameSpace(type, typeof(My.Other.NameSpace.IContract));
        }

        private bool IsFromNameSpace(Type type, Type contract)
        {
            type.Namespace == contract.NameSpace;
        }
    }
}

usage:

if (type.IsFromFunNameSpace())
{
    // do stuff
}

Anyway your IOC approach looks weired to me. The ultimate solution (which requires you to have access to the source code) would be to just let a class implement an interface (which can be empty)

public interface IFun { }

public class FunnyClass : IFun { }

usage:

if (typeof(IFun).IsAssignableFrom(type))
{
    // do stuff
}

Now you are not limited to a specific namespace

Related Topic