Search code examples
c#lambdaexpression-trees

Expression Tree and Compile method


This is all about the Compile method of Expression Type. Sorry being naïve since I am a late comer. I have been reading about building expression in order to enables dynamic modification of executable code. And It make sense for me when it comes to emitting lambda expression from a given expression tree as long as for the varying inputs/environment (say for different values for any given constant/parameter/member expression). I presume, it would be ideal if I could cache (re-use) lambda those are generated/compiled from an expression tree provided there is no change in the environment.

Question: Does CLR always emit lambda expression even if I have there is no change in the environment? If so, what is the best was to avoid compilation of expression from lambda if there is no change in the environment?


Solution

  • Lambda expressions is just a way to represent a piece of code: call this, call that, compare these arguments, return something, etc. Almost the same way you do it from code editor, or JIT does from IL.

    Compile emits a delegate from particular lambda expression. Once you have compiled lambda into delegate, the delegate remains unchanged (the lambda remains unchanged too, because it is immutable).

    This doesn't mean, that delegate can't accept any arguments or call any method of any object. This just means, that delegate's IL doesn't change. And yes, you can cache compiled delegate instance.