Thursday, August 20, 2009

Lambdas and Anonymous Delegates pt 2

So I did exactly what I suggested to myself, and sent an email to Eric Lippert regarding the inline lambda and anonymous delegate business I blogged about earlier today. He's quick - here's his reply:

Ah, good question.

You can make this work by casting to a delegate type.

((Func<bool>)()=>M()).Invoke();
((Func<bool>)(delegate (){return M();}).Invoke();

For lambdas, we don't know whether the lambda is to be converted to a delegate or an expression tree. Since an expression tree cannot be invoked, we cannot allow you to invoke it before we know what you intend.

For anonymous methods, yeah, I suppose we could have designed C# 2.0 to allow invoking them directly. But what would the point be? Why say (delegate(){return M();}).Invoke()" when you could just say "M()"? I agree that for reasons of generality and consistency it would be nice to have, but I don't think disallowing this actually disables many scenarios.


He's right - it's not like this is some sort of necessary functionality. On the one hand, it's great that I can get exactly this functionality by casting to a delegate type first, but on the other hand it's extra cruft. All the same, if some inspired or courageous EverDroid user needs this sort of functionality, it's there.

Thanks, Eric! =)

No comments: