Consider the following classes hierarchy: base class A, classes B and C inherited from A and class D inherited from B.
public class A {...}
public class B : A {...}
public class C : A {...}
public class D : B {...}
I can use following code to find all subclasses of A including D:
var baseType = typeof(A);
var assembly = typeof(A).Assembly;
var types = assembly.GetTypes().Where(t => t.IsSubclassOf(baseType));
But I need to find only direct subclasses of A (B and C in example) and exclude all classes not directly inherited from A (such as D). Any idea how to do that?
If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__ as above. However you find the class, cls. __subclasses__() would then return a list of its subclasses.
Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties.
Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
For each of those types, check if
type.BaseType == typeof(A)
Or, you can put it directly inline:
var types = assembly.GetTypes().Where(t => t.BaseType == typeof(baseType));
Use Type.BaseType for that. From the documentation:
The base type is the type from which the current type directly inherits. Object is the only type that does not have a base type, therefore null is returned as the base type of Object.
Just compare them appropriately:
var types = assembly.GetTypes().Where(t => t.BaseType == baseType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With