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

31,963

Solution 1

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;

Solution 2

Subclasses meaning interfaces? Yes:

this.GetType().GetInterfaces()

Subclasses meaning base types? Well, c# can only have one base class

Subclasses meaning all classes that inherit from your class? Yes:

EDIT: (thanks vcsjones)

foreach(var asm in AppDomain.CurrentDomain.GetAssemblies())
{
        foreach (var type in asm.GetTypes())
        {
            if (type.BaseType == this.GetType())
                yield return type;
        }
}

And do that for all loaded assemblies

Share:
31,963
Adam Lee
Author by

Adam Lee

Updated on October 20, 2020

Comments

  • Adam Lee
    Adam Lee over 3 years

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