62

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

S2S2
  • 8,322
  • 5
  • 37
  • 65
Adam Lee
  • 24,710
  • 51
  • 156
  • 236

2 Answers2

89

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;

mtijn
  • 3,610
  • 2
  • 33
  • 55
  • 2
    To do the same thing for an interface instead of an object/class, change the where line to `where typeof(IMyInterface).IsAssignableFrom(type) && type.IsClass` ([original question](http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface-with-c-sharp-3-0)). – jtpereyda Dec 02 '13 at 21:26
5

To get subclasses:

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

You also can get interfaces:

this.GetType().GetInterfaces()

And to do the opposite (get the base class), C# can only have one base class.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
joe_coolish
  • 7,201
  • 13
  • 64
  • 111
  • Aside from the subclass definition issues, this answer doesn't address the question because it won't return subclasses that are more than 1 level away in the hierarchy. – Mike Marynowski Nov 13 '18 at 21:05