Adam Lee Adam Lee - 1 year ago 129
C# Question

For an object, can I get all its subclasses using reflection or other ways?

For an object, can I get all its subclasses using reflection?

Answer Source

You can load all types in the Assembly and then enumerate them to see which ones implement the type of your object. You said 'object' so the below code sample is not for interfaces. Also, this code sample only searches the same assembly as the object was declared in.

class A
typeof(A).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(A)));

Or as suggested in the comments, use this code sample to search through all of the loaded assemblies.

var subclasses =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
    from type in assembly.GetTypes()
    where type.IsSubclassOf(typeof(A))
    select type

Both code samples require you to add using System.Linq;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download