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.

ouflak
  • 2,458
  • 10
  • 44
  • 49
Krzysztof Madej
  • 32,704
  • 10
  • 78
  • 107
  • possible duplicate of [How to check if implicit or explicit cast exists?](http://stackoverflow.com/questions/1815452/how-to-check-if-implicit-or-explicit-cast-exists) – nawfal Jan 18 '14 at 07:27

2 Answers2

10

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);
            }
        }
MikkaRin
  • 3,026
  • 19
  • 34
-4

Have you tried IsAssignableFrom?

Type type = typeof(MyClass);
type.IsAssignableFrom(typeof(MyOtherClass));
Artless
  • 4,522
  • 1
  • 25
  • 40
  • 2
    This doesn't seem to work for implicit conversions. See also the first answer here: http://stackoverflow.com/questions/2119441/check-if-types-are-castable-subclasses. – Magnus Grindal Bakken Aug 15 '13 at 11:15
  • It's wrong! Long is assignable from Short, `long x = new short();`, but `typeof(long).IsAssignableFrom(typeof(short))` returns False! – Colonel Panic Apr 01 '14 at 15:11