zmbq
zmbq

Reputation: 39023

TryConvert doesn't get called when casting through object

I have a DynamicObject with an implemented TryConvert method. The following code works well:

dynamic d = GetMyDynamic();
int i = (int)d;   // TryConvert is called and returns the proper int value

However, when d is cast to object, the conversion fails at runtime:

object o = d;
int i = (int)o;  // TryConvert is not called. InvalidCastException thrown

Of course, (int)(dynamic)o does work, as expected.

Why is that? And is there any way to work around that so that (int)o will call TryConvert?

Upvotes: 1

Views: 332

Answers (2)

Vyacheslav Volkov
Vyacheslav Volkov

Reputation: 4742

I fully agree with the Daniel Hilgarth. To better understand why this is so consider the example of an overload operators:

public class TestClass
{
    public static explicit operator int(TestClass d)
    {
        return 1;
    }
}

var testClass = new TestClass();
object obj = testClass;
var value = (int)testClass;//No exceptions here, because the CLR knows how to cast TestClass to int.
var i = (int)obj;//Exception here, because the CLR doesn't know how to cast object to int.

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174339

The reason is actually pretty simple: If you don't use the dynamic keyword the Dynamic Language Runtime (DLR) is not used. But the Dynamic Language Runtime is what calls the TryConvert method.

Without the DLR, o is just an object of type MyDynamicObject that you are trying to cast to int. That fails, because MyDynamicObject is not an int.

Upvotes: 2

Related Questions