Cool Code – Assembly.FindType

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

        }

    }

This entry was posted in c#. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>