#727 – Get a List of All Namespaces in an Assembly

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();
            }
        }

727-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: