Krzysztof Madej
Krzysztof Madej

Reputation: 40673

How to check if an implicit conversion is available between types?

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.

Upvotes: 4

Views: 1954

Answers (2)

MikkaRin
MikkaRin

Reputation: 3084

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);
            }
        }

Upvotes: 11

Artless
Artless

Reputation: 4568

Have you tried IsAssignableFrom?

Type type = typeof(MyClass);
type.IsAssignableFrom(typeof(MyOtherClass));

Upvotes: -4

Related Questions