PrimeDigit – A Design Blog by Will Shaver

June 4, 2008

Cool Code – Assembly.FindType

Filed under: c# — Will @ 3:06 pm

Here’s an extension to Assembly that I found useful for finding a type. I recommend doing
typeof(TypeInAssembly).Assembly.FindType(“typename”);

    public static class AssemblyExtensions

    {

        public static Type FindType(this Assembly assembly, string typename)

        {

            return assembly.FindTypes(typename).FirstOrDefault();

        }

 

        public static Type[] FindTypes(this Assembly assembly, string typename)

        {

            Type[] types = assembly.GetExportedTypes();

            List<Type> found = new List<Type>();

            foreach(Type type in types)

            {

                if(type.Name == typename)

                {

                    found.Add(type);

                }

            }

            return found.ToArray();

        }

    }

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress