DynamicObject implicit casting
Asked Answered
F

2

6

I have a subclass of DynamicObject and I would like to implement implicit casting for primitive types similarly as DO's explicit casting method TryConvert; that is, without writing multiple implicit operator [type] functions.

Usage:

dynamic myDynamicObject = new MyDynamicObject("1");
int sum = 1 + myDynamicObject; // instead of int i = 1 + (int)myDynamicObject;

Is that possible and if so, how?

Fairish answered 16/1, 2010 at 0:29 Comment(0)
R
6

There are several things going on here.

First, you are performing a binary operation. So, you need to override TryBinaryOperation method as well. It will be called first, before conversion. Then from the TryBinaryOperation method you can perform a conversion.

Second, for whatever reason the TryBinaryOperation is called only if you write a statement like this:

int sum = myDynamicObject + 1;

From what I see now, the order is important. I'll check with the DLR team whether it is a bug or intended behavior.

Update: It's not a bug. To support both "1 + myDynamicObject" and "myDynamicObject + 1" you need not only TryBinaryOperation, but also something like TryBinaryOperationFromRight, which the current DynamicObject simply does not have.

Rego answered 18/1, 2010 at 19:54 Comment(2)
With implicit cast in "1+myDynamicObject" scenario it uses the left sides operation on the cast type; in this case ints operation +(int,int). But yes, TryBinaryOperation supports only left-side operations. That's why similar method of implicit casting as TryConvert for explicit casting would be very useful.Fairish
TryConvert in fact supports both implicit and explicit casting. For example, this works fine: "int sum = myDynamicObject;" if you override the TryConvert. But when you perform a binary operation (and I guess a unary as well), the TryConvert method is not called. I'd suggest you to write to [email protected] and explain your use case there. It might be a bug or there might be some design rational behind this, which the team can explain better than me.Rego
F
3

DLR-team answered my question and said that it isn't possible when DO is the right-hand operand.

Quoted from their answer: "The foremost rule is that the dynamic object needs to be the left hand operand because the dynamic operations protocol only works with the dynamic object in that position."

Left-hand implicit casting can be done through TryBinaryOperation, but for that you have to also implement the supported operators (+,-,...).

Fairish answered 20/1, 2010 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.