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('.'))

        var largestCommonality = 0;

            if(largestCommonality >= splitNamespaces[0].Length)

            var valueToTest = splitNamespaces[0][largestCommonality];
            var commonality = largestCommonality;
            var areAllSame = splitNamespaces.All(strings => strings.Length > commonality && strings[commonality] == valueToTest);
        } 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