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?

2 Answers 2

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.

7
  • This is interesting and surprising; I'm on mobile at the moment, but I must look at this later! Aug 12, 2011 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, 2011 at 17:27
  • @ShdNx - the odd thing is you could return a string if you wanted to.
    – vcsjones
    Aug 12, 2011 at 17:48
  • the problem is that you can't have a lambda expression as a dynamic Is there an explanation for that? Aug 12, 2011 at 18:19
  • 4
    This intrigued me - you are absolutely right that this is possible; wrote up my example here: marcgravell.blogspot.com/2011/08/… Aug 12, 2011 at 20:46
2
dynamic MyObject = new MyDynamicClass();
MyObject >>= new Func<int>(() => 1 + 1);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.