Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .net reflection to find a common ancestor class

Tags:

c#

reflection

I have an assembly containing types that have a common ancestor class (defined within the assembly. The common ancestor is in most cases not the class's immediate base type.

I need to be able to filter out, from all the types in this assembly, those with this common ancestor. For various reasons I can't instantiate the types (they do not as a rule have a common constructor signature) so I have to start with myAssembly.GetTypes() and examine the properties of the types themselves. In other words I have to work with classes, not instances of the classes.

How do I examine each Type in this collection to find if it inherits from the desired common ancestor or not?

Later: no worries, I have it now. The trick is to instantiate a type object that is the ancestor type from the assembly, eg

Type ancestor = assy.getType("myAncestorClassName", true, true);
Type[] interestingClasses = assy.GetTYypes().Where(t => t.IsSubclassOf(ancestor));

However this will not work:

Type[] interestingClasses = assy.GetTYypes().Where(t => t.IsSubclassOf(typeof(AncestorClass)));

because, I think, the ancestor type is defined in the other assembly and not in the main assembly.

Much, much later....Thanks to everyone who contributed answers to this. I was diverted to something else along the way, but I now have a neat solution (and have learned something new).

like image 839
haughtonomous Avatar asked Jan 18 '23 12:01

haughtonomous


2 Answers

For each type in your collection, you can see if they derive from this ancestor by using Type.IsAssignableFrom.

For example:

var types = assembly.GetTypes().Exclude(t => typeof(CommonAncestor).IsAssignableFrom(t));

This should get all types in the assembly which aren't derived from CommonAncestor.

like image 200
Lukazoid Avatar answered Jan 27 '23 10:01

Lukazoid


Use Type.IsAssignableFrom to find out if one type is assignable from an instance of another type.

like image 27
Botz3000 Avatar answered Jan 27 '23 12:01

Botz3000