Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C#
Tip/Trick

Locate derived types in assemblies

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
29 Dec 2011CPOL 14.4K   2  
Locate all the derived types of a type in a given assembly.

Shamelessly nicked from http://www.codemeit.com/code-collection/c-find-all-derived-types-from-assembly.html[^] but extended and tidied, this simple pair of extension methods locate all the derived types of a type in a given assembly. Also, I added the ability to locate a type by name, since sometimes you can't find the namespace, or don't care.


C#
public static class LocateStuffInAssembliesExtension
{
    public static Type FindTypeFromAssembly(this Assembly assembly,
        string name)
    {
        var types = assembly.GetTypes();
        return types.SingleOrDefault(t => t.Name == name);
    }

    public static IEnumerable<Type> FindDerivedTypesFromAssembly(this Assembly assembly,
        Type baseType,
        bool classOnly)
    {
        var types = assembly.GetTypes();
        foreach (var type in types.Where(type => !classOnly || type.IsClass))
        {
            if (baseType.IsInterface)
            {
                var it = type.GetInterface(baseType.FullName);

                if (it != null)
                {
                    yield return type;
                }
            }
            else if (type.IsSubclassOf(baseType))
            {
                yield return type;
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --