Click here to Skip to main content
Click here to Skip to main content

Tagged as

Locate derived types in assemblies

, 29 Dec 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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)

Share

About the Author

Gizz
Architect
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.141015.1 | Last Updated 29 Dec 2011
Article Copyright 2011 by Gizz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid