Conversion from Lambda to Expression Tree

c# expression-trees lambda

Question

I will keep it really simple,

How do I get expression tree out of lambda??

or from query expression ?

1
39
8/21/2009 12:49:21 PM

Accepted Answer

You must assign the lambda to a different type:

// Gives you a delegate:
Func<int, int> f = x => x * 2;
// Gives you an expression tree:
Expression<Func<int, int>> g = x => x * 2;

The same goes for method arguments. However, once you've assigned such a lambda expression to a Func<> type, you can't get the expression tree back.

57
12/18/2013 7:33:33 PM

Popular Answer

Konrad's reply is exact. You need to assign the lambda expression to Expression<Func<...>> in order for the compiler to generate the expression tree. If you get a lambda as a Func<...>, Action<...> or other delegate type, all you have is a bunch of IL instructions.

If you really need to be able to convert an IL-compiled lambda back into an expression tree, you'd have to decompile it (e.g. do what Lutz Roeder's Reflector tool does). I'd suggest having a look at the Cecil library, which provides advanced IL manipulation support and could save you quite some time.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow