There\'s IsAssignableFrom
method returns a boolean value indicates if one type is assignable from another type.
How can we not only test if they are as
The simplest case would be iterating over the base types of one object and checking them for being assignable with the other type, like this:
Code
public Type GetClosestType(Type a, Type b) {
var t=a;
while(a!=null) {
if(a.IsAssignableFrom(b))
return a;
a=a.BaseType;
}
return null;
}
This will produce System.Object
for two types which are unrelated, if they are both classes. I'm not sure if this behaviour met your requirement.
For more advanced cases, I'm using a custom extension method called IsExtendablyAssignableFrom
.
It can handle different numeric types, generics, interfaces, generic parameters, implicit conversions, nullable, boxing/unboxing, and pretty much all the types I have come across with when implementing my own compiler.
I've uploaded the code into a separate github repository [here], so you could use it in your project.