I have an assembly, and I want to list all classes that inherit from a specific class/interface.
How would I do this?
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...)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With