Implicit version of IsAssignableFrom?

In my code using reflections I wrote

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

I have a class that has implicit conversion to strings. However, the above if statement will not catch it. How can I do reflection / above if the catch statement of strings and classes with implicit string conversion? instead of specific lines and every class that I know of?

+6
reflection c # implicit-cast
source share
2 answers

I would use an extension method that gets all public static methods and validates the 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; } } 
+7
source share
 if(... || TypeDescriptor.GetConverter(f).CanConvertTo("".GetType())) 
0
source share

All Articles