Reputation: 103487
I have an assembly, and I want to list all classes that inherit from a specific class/interface.
How would I do this?
Upvotes: 6
Views: 2368
Reputation: 1499860
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...)
Upvotes: 7
Reputation: 292375
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;
}
Upvotes: 3