13

I can't seem to apply binary operations to lambda expressions, delegates and method groups.

dynamic MyObject = new MyDynamicClass();
MyObject >>= () => 1 + 1;

The second line gives me error: Operator '>>=' cannot be applied to operands of type 'dynamic' and 'lambda expression'

Why?

Isn't the operator functionality determined by my custom TryBinaryOperation override?

Conrad Clark
  • 4,533
  • 5
  • 45
  • 70

2 Answers2

13

It's not an issue with MyDynamicClass, the problem is that you can't have a lambda expression as a dynamic. This however, does appear to work:

dynamic MyObject = new MyDynamicClass();
Func<int> fun = () => 1 + 1;
var result = MyObject >>= fun;

If the TryBinaryOperation looks like this:

result = ((Func<int>) arg)();
return true;

Then result will be 2. You can use binder.Operation to determine which binary operation this is.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • This is interesting and surprising; I'm on mobile at the moment, but I must look at this later! – Marc Gravell Aug 12 '11 at 17:12
  • @Marc Gravell: I think the restriction that the second operand must be an int is enforced only when you define the operator, and not when you use it. – ShdNx Aug 12 '11 at 17:27
  • @ShdNx - the odd thing is you could return a string if you wanted to. – vcsjones Aug 12 '11 at 17:48
  • `the problem is that you can't have a lambda expression as a dynamic` Is there an explanation for that? – Conrad Clark Aug 12 '11 at 18:19
  • @Conrad: Likely for the [same reason](http://stackoverflow.com/questions/4965576/c-why-cant-an-anonymous-method-be-assigned-to-var) you can't declare a lambda as var. It's *possible*, but the functionality isn't there. – vcsjones Aug 12 '11 at 18:59
  • @Conrad - there would be no default delegate-type or `T` in `Expression` - you'd need the compiler to assume (for example) `Action<...>`/`Func<...>` - possible, but not necessarily desirable. – Marc Gravell Aug 12 '11 at 20:46
  • 4
    This intrigued me - you are absolutely right that this is possible; wrote up my example here: http://marcgravell.blogspot.com/2011/08/shifting-expectations-non-integer-shift.html – Marc Gravell Aug 12 '11 at 20:46
2
dynamic MyObject = new MyDynamicClass();
MyObject >>= new Func<int>(() => 1 + 1);
jbtule
  • 31,383
  • 12
  • 95
  • 128