infoof and tricks with expression trees

Chapter 9: Lambda expressions and expression trees: 9.3.3

Created: 3/4/2008
Last updated: 3/10/2008

Eric reveals a feature which has been under discussion:

We have for many years considered creating an infoof (pronounced "in foof", of course) operator that would be to MethodInfos as typeof is to Types. The problem is, how do you specify the arguments so that overload resolution can select the correct method out of the method group? There’s no good way to do it, and there have always been way more important things to do, so it keeps getting cut.

However, the fact that lambda expression conversions can use the IL methodinfo operator can be used to your advantage:

If you want to get a methodinfo for a particular method, you can just say

Expression<Func<int,string,double>> e = (arg1, arg2)=>M(arg1, arg2);

And then pull the MethodInfo out of the generated Call node! Of course you end up with a few wasted object allocations along the way, but you are guaranteed to get the same method out that the compiler would have picked for overload resolution.

Interestingly, I'm pretty sure Marc Gravell came up with exactly the same idea after I'd read Eric's note, but before I included it on this web site.