Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a type supports an implicit or explicit type conversion to another type with .NET

Imagine you've been given two System.Type's and you want to determine if there is an implicit or explicit type conversion from one to the other.

Without specifically checking for the static methods is there a built in method to determine that the type supports either or these conversions?

I know this is a brief body to a question but I think the scenario is relatively easy to explain, let me know if not.

Thanks in advance, Stephen.

like image 817
meandmycode Avatar asked Sep 05 '10 17:09

meandmycode


2 Answers

Expression.Convert can look for a user-defined conversion operator, but unfortunately it will just throw an exception if none is found. You could use it like this:

public static bool CanConvert(Type fromType, Type toType)
{
    try
    {
        // Throws an exception if there is no conversion from fromType to toType
        Expression.Convert(Expression.Parameter(fromType, null), toType);
        return true;
    }
    catch
    {
        return false;
    }
}
like image 183
Quartermeister Avatar answered Oct 23 '22 15:10

Quartermeister


I don't think so. You'll have use reflection and look for those good ol' op_Implicit and op_Explicit static methods on each type.

This brings up the very interesting question: which has a greater performance impact, reflection (this answer) or using exceptions for control flow (Quartermeister's)? I honestly couldn't guess. You might want to profile each and find out for yourself.

like image 35
Dan Tao Avatar answered Oct 23 '22 14:10

Dan Tao