Finding all Namespaces in an assembly using Reflection (DotNET)

No, there’s no shortcut for this, although LINQ makes it relatively easy. For example, in C# the raw “set of namespaces” would be:

var namespaces = assembly.GetTypes()
                         .Select(t => t.Namespace)
                         .Distinct();

To get the top-level namespace instead you should probably write a method:

var topLevel = assembly.GetTypes()
                       .Select(t => GetTopLevelNamespace(t))
                       .Distinct();

...

static string GetTopLevelNamespace(Type t)
{
    string ns = t.Namespace ?? "";
    int firstDot = ns.IndexOf('.');
    return firstDot == -1 ? ns : ns.Substring(0, firstDot);
}

I’m intrigued as to why you only need top level namespaces though… it seems an odd constraint.

Leave a Comment