4

I need to check if an implicit conversion is available between types. For built-in types, I can create a dictionary with a type and list of corresponding available types. But for custom types this is not possible because I don't know on what code this will be checked. Is there a generic way to do this?

Thanks.

1

2 Answers 2

11

Try this. If for custom type defined method for implicit conversation, you will find it by "op_Implicit" name

foreach (MethodInfo mi in typeof(CustomType).GetMethods())
        {
            if (mi.Name == "op_Implicit")
            {
                Console.WriteLine(mi.ReturnType.Name);
            }
        }
3
  • 3
    Note that the inbuilt types often don't contain operators - their conversions are done at the IL level. So while this is part of the answer, some conversions typically need to be hard-coded Commented Aug 15, 2013 at 10:57
  • This code with definitions for inbuilt types works great. Great thanks! Commented Aug 15, 2013 at 13:21
  • Thanks. However, is there any way to do this without reflection?
    – krimog
    Commented Nov 16, 2015 at 13:54
-4

Have you tried IsAssignableFrom?

Type type = typeof(MyClass);
type.IsAssignableFrom(typeof(MyOtherClass));
2
  • 2
    This doesn't seem to work for implicit conversions. See also the first answer here: stackoverflow.com/questions/2119441/…. Commented Aug 15, 2013 at 11:15
  • It's wrong! Long is assignable from Short, long x = new short();, but typeof(long).IsAssignableFrom(typeof(short)) returns False! Commented Apr 1, 2014 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.