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?

denfromufa
  • 5,610
  • 13
  • 81
  • 138
Toni Kielo
  • 93
  • 7

2 Answers2

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.

Alexandra Rusina
  • 10,991
  • 2
  • 20
  • 16
  • 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. – Toni Kielo Jan 19 '10 at 07:10
  • 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 dlr@microsoft.com 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. – Alexandra Rusina Jan 19 '10 at 18:19
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 (+,-,...).

Toni Kielo
  • 93
  • 7