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).
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.
Use Type.IsAssignableFrom to find out if one type is assignable from an instance of another type.
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