#726 – Listing all Types within a Namespace

You can’t directly list out all types within a namespace.  But you can get all types within a particular assembly and then filter out only the types that match a particular namespace.

        static void Main()
        {
            // Dump all types from in a specified namespace
            DumpTypesForNamespace(Assembly.GetExecutingAssembly(), "ConsoleApplication1");
            DumpTypesForNamespace(Assembly.GetExecutingAssembly(), "ConsoleApplication1.Dog");

            int i = 1;
        }

        private static void DumpTypesForNamespace (Assembly assem, string theNamespace)
        {
            Console.WriteLine(string.Format("[{0}]", theNamespace));

            foreach (Type t in assem.GetTypes())
            {
                if (t.Namespace == theNamespace)
                {
                    string dump =
                        string.Format("{0}\n  ({1} in {2})\n", t.FullName, TypeIndicator(t), t.Namespace);

                    Console.WriteLine(dump);
                }
            }
            Console.WriteLine("\n");
        }

        private static string TypeIndicator(Type t)
        {
            string typeIndicator = "?";

            if ((t.BaseType != null) &&
                (t.BaseType.FullName == "System.MulticastDelegate"))
                typeIndicator = "delegate";

            else if (t.IsClass)
            {
                if (t.IsNested)
                    typeIndicator = "Nested class";
                else
                    typeIndicator = "class";
            }
            else if (t.IsInterface)
                typeIndicator = "interface";

            else if (t.IsValueType)
                typeIndicator = "struct";

            else if (t.IsEnum)
                typeIndicator = "enum";

            return typeIndicator;
        }

726-002

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: