List of all classes that inherit from a specific class / interface

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

How can I do it?

+6
c #
source share
2 answers

Something like:

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

This is good for a simple case, but it becomes more "interesting" (read: difficult) when you want to find "all types that implement IEnumerable<T> for any T ", etc.

(As Adam says, you can easily do this with an extension method. It depends on whether you think you are reusing it or not - this is a pain that extension methods should be in a non-nested static class ...)

+7
source share
 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; } 
+3
source share

All Articles