Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all direct subclasses of a class with .NET Reflection

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?

like image 325
mykola Avatar asked Apr 16 '13 13:04

mykola


People also ask

How do you find all the subclasses of a class given its name?

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.

What is .NET reflection?

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.

What are subclasses C#?

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.


3 Answers

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)); 
like image 157
zimdanen Avatar answered Dec 09 '22 06:12

zimdanen


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.

like image 41
Toni Petrina Avatar answered Dec 09 '22 06:12

Toni Petrina


Just compare them appropriately:

var types = assembly.GetTypes().Where(t => t.BaseType == baseType);
like image 36
Euphoric Avatar answered Dec 09 '22 06:12

Euphoric