Finding a common namespace root for an assembly

“What’s the difference between a namespace and an assembly?”

It’s a very standard interview question and I’m sure we can all answer that one easily.  And so we all know that it’s possible for an assembly to contain types from a variety of namespaces and that these namespaces may or may not have anything in common with each other.

But in the real world, types within an assembly typically do have something in common with each other.  And usually there is a common portion of the namespace names.  And in case you want to work out what that common portion is, here is some code:

public static class AssemblyHelper
{
    public static string DeduceRootNamespaceParts(Assembly assembly)
    {
        var splitNamespaces = assembly.GetTypes()
            .Where(type => type.IsPublic)
            .Select(type => type.Namespace.Split('.'))
            .ToArray();

        var largestCommonality = 0;

        do
        {
            if(largestCommonality >= splitNamespaces[0].Length)
                break;

            var valueToTest = splitNamespaces[0][largestCommonality];
            var commonality = largestCommonality;
            var areAllSame = splitNamespaces.All(strings => strings.Length > commonality && strings[commonality] == valueToTest);
            if(!areAllSame)
                break;
            largestCommonality++;
        } while (true);

        return String.Join(".", splitNamespaces[0].Take(largestCommonality).ToArray());
    }
}

I suspect that this code is O(n) complexity with regard to the number of types contained in the assembly, but I haven’t thought about it terribly deeply.

April 28 2010
blog comments powered by Disqus