Click here to Skip to main content
12,355,960 members (70,802 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

10.9K views
2 bookmarked
Posted

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

You may also be interested in...

Comments and Discussions

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