I have two types, T and U, and I want to know whether an implicit cast operator is defined from T to U.
I\'m aware of the existence of IsAssignableFrom, and this is not
You could use reflection to find the implicit conversion method for the target type:
public static bool HasImplicitConversion(Type baseType, Type targetType)
{
return baseType.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType)
.Any(mi => {
ParameterInfo pi = mi.GetParameters().FirstOrDefault();
return pi != null && pi.ParameterType == baseType;
});
}
You can use it like this:
class X {}
class Y
{
public static implicit operator X (Y y)
{
return new X();
}
public static implicit operator Y (X x)
{
return new Y();
}
}
// and then:
bool conversionExists = HasImplicitConversion(typeof(Y), typeof(X));
Note that this only checks for an implicit type conversion on the base type (the first passed type). Technically, the type conversion can also be defined on the other type, so you may need to call it again with the types reversed (or build that into the method). Implicit type conversions may not exist on both types though.