I have two System.Type objects, say, a and b. I need a way to know whether the type represented by a can be casted to the type represented by b. For instance, if:
a = typeof(int)
b = typeof(double)
An int can be casted to a double , so the condition would be true.
I considered a.IsAssignableTo(b), but that only detects if either a == b or a is descended from b, not if a user-defined conversion exists.
Any suggestions would be greatly appreciated.
Bear in mind that have only the System.Type objects for the two types, no instances or generic type parameters. This is not a duplicate of other questions where they already have instances of the type in question, such as How to check if type can be converted to another type in C#.
You can do it by testing it. If you have no instance of the types, you might create a default instance using
Activator.The assignment test can be handled through some
MakeGenericType/MakeGenericMethodreflection magic.As for the int to double (OK) and double to int (NOK) example, this shows how to do it (See also on netfiddle https://dotnetfiddle.net/1MBNxg ):