How to find all direct subclasses of a class with .NET Reflection
12,136
Solution 1
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));
Solution 2
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.
Solution 3
Just compare them appropriately:
var types = assembly.GetTypes().Where(t => t.BaseType == baseType);
Related videos on Youtube
Author by
mykola
Updated on October 19, 2022Comments
-
mykola over 1 year
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?
-
zimdanen almost 11 yearsI don't think this is correct - this would return none, assuming we're looking for descendants of
A
, becauseA.BaseType
isObject
(see Toni Petrina's answer for the documentation on that). This should bet.BaseType == baseType
or compiling equivalent. -
Euphoric almost 11 yearsRight. Wasn't paying attention after first answer came in.
-
Chris Sinclair almost 11 yearsNot sure if you want
typeof(t)
there; won't that result inSystem.Type
sincet
is already theSystem.Type
representingA
,B
,D
, etc? EDIT: No, I'm silly, that's just a compiler error instead! -
zimdanen almost 11 years@ChrisSinclair: Changed to use
type
andt
directly. Thanks; don't have VS in front of me to verify currently. -
mykola almost 11 yearsthanks! I've missed BaseType property. Additionally, any idea how to get all first non-abstract subclasses of a class? In my sample if B is abstract then I want C and D.
-
zimdanen almost 11 years@mykola: Off the top of my head, not sure how to do so without using recursion and checking Type.IsAbstract. You may want to start a new question for that.
-
zimdanen almost 11 years@mykola: Plus, you then have you then have to consider what "first" means. (
B : A
,F : B
,G : B
- ifB
is abstract and bothF
andG
aren't, do you want a deterministic answer? Do you want both to appear?) -
mykola almost 11 yearsThanks, @zimdanen, I have enough info to figure it out! I need all of them. Maybe "all first" in my comment doesn't explain it well.