Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all classes that inherit from a specific class/interface

Tags:

c#

I have an assembly, and I want to list all classes that inherit from a specific class/interface.

How would I do this?

like image 907
mrblah Avatar asked Aug 17 '09 13:08

mrblah


Video Answer


2 Answers

Something like:

public static IEnumerable<Type> GetSubtypes(Assembly assembly, Type parent)
{
    return assembly.GetTypes()
                   .Where(type => parent.IsAssignableFrom(type));
}

That's fine for the simple case, but it becomes more "interesting" (read: tricky) when you want to find "all types implementing IEnumerable<T> for any T" etc.

(As Adam says, you could easily make this an extension method. It depends on whether you think you'll reuse it or not - it's a pain that extension methods have to be in a non-nested static class...)

like image 180
Jon Skeet Avatar answered Sep 25 '22 10:09

Jon Skeet


public static IEnumerable<Type> GetTypesThatInheritFrom<T>(this Assembly asm)
{
    var types = from t in asm.GetTypes()
                where typeof(T).IsAssignableFrom(t)
                select t;
    return types;
}
like image 34
Thomas Levesque Avatar answered Sep 23 '22 10:09

Thomas Levesque