Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find types that are direct descendants of a base class?

I need to get all types of an assembly that inherits some base class but only the first descendants. For instance if I have:

class Base
{

}

class FirstClass : Base
{

}

class SecondClass : FirstClass
{

}

Now

var directOnes = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Base)));

should return only FirstClass and not SecondClass. Is there a way to find out?

like image 349
nawfal Avatar asked Mar 24 '23 00:03

nawfal


1 Answers

Instead of IsSubclassOf() you can use Type.BaseType

e.g.

var directOnes = assembly.GetTypes().Where(t => t.BaseType == (typeof(Base)));

(FYI: I don't think there's a way to find the interfaces that a type directly implements.)

like image 106
Matthew Watson Avatar answered Apr 14 '23 14:04

Matthew Watson