#727 – Get a List of All Namespaces in an Assembly
December 3, 2012 Leave a comment
While you can’t explicitly get a list of all namespaces within a .NET assembly, you can iterate through all types in the assembly and build up a list of namespaces.
Below is some sample code that organizes all types in an assembly, by namespace.
static void Main() { // Build list of all types : // SortedList<namespace-name, SortedList<type-name, Type>> SortedList<string, SortedList<string, Type>> myTypeList = ExtractListOfTypes(Assembly.GetExecutingAssembly()); DumpTypeList(myTypeList); } private static SortedList<string, SortedList<string, Type>> ExtractListOfTypes(Assembly assem) { SortedList<string, SortedList<string, Type>> theList = new SortedList<string, SortedList<string, Type>>(); foreach (Type t in assem.GetTypes()) { // Add namespace if it's not already in list if (!theList.ContainsKey(t.Namespace)) theList.Add(t.Namespace, new SortedList<string, Type>()); // And add type under appropriate namespace theList[t.Namespace].Add(t.FullName, t); } return theList; } private static void DumpTypeList(SortedList<string, SortedList<string, Type>> theList) { foreach (KeyValuePair<string,SortedList<string,Type>> kvp in theList) { Console.WriteLine(string.Format("Namespace: [{0}]", kvp.Key)); foreach (KeyValuePair<string, Type> kvpInner in kvp.Value) { Console.WriteLine(string.Format(" Type: [{0}]", ((Type)kvpInner.Value).FullName)); } Console.WriteLine(); } }