For an object, can I get all its subclasses using reflection or other ways?
C#.NetInheritanceReflectionC# Problem Overview
For an object, can I get all its subclasses using reflection?
C# Solutions
Solution 1 - C#
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 - C#
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.