views:

107

answers:

2

In my code using reflections i wrote

if (f.FieldType.IsAssignableFrom("".GetType()))

I have a class that has an implicit conversion to strings. However the if statement above doesnt catch it. How can i make reflection/the above if statement catch strings and classes with implicit string conversion? instead of specifically strings and each class i know about?

A: 
if(... || TypeDescriptor.GetConverter(f).CanConvertTo("".GetType()))
SwDevMan81
Problem here is it seems to converts EVERYTHING to string. Including non implicit classes. The fact it converts classes to a string ruins my code.
acidzombie24
+2  A: 

I would use an extension method which gets all public static methods and checks for a method with the correct name and return type.

public static class TypeExtentions
{
    public static bool ImplicitlyConvertsTo(this Type type, Type destinationType)
    {

        if (type == destinationType)
            return true;


        return (from method in type.GetMethods(BindingFlags.Static |
                                               BindingFlags.Public)
                where method.Name == "op_Implicit" &&
                      method.ReturnType == destinationType
                select method
                ).Count() > 0;
    }
}
Courtney de Lautour
Yup. Implicit conversion operators are just syntactic sugar. They don't have any special meaning to the CLR, and VB.NET doesn't even understand them (or at least it didn't in the past). It's not a true cast, and therefore it is not truly assignable; the only answer is to actually check for the implicit operator.
Aaronaught