I want to have several routines which are dynamically created using Expression trees. It seems that the easiest way to use them would be to create LambdaExpression
and then call LambdaExpression
.
Compile()
resulting in a callable delegate.
Compile()
?TypeBuilder
and MethodBuilder
?Any suggestions are welcome!
DynamicMethod
is generated - which is a standalone method that avoids all the usual weight of AssemblyBuiler
, ModuleBuilder
, TypeBuilder
etc, and just provides raw access to an ILGenerator
to a static
-style method; the code then walks the expression tree, emitting the appropriate op-codes via ILGenerator
; finally, CreateDelegate
is called on the DynamicMethod
DynamicMethod
tries to avoid thisDynamicMethod
can do that TypeBuilder
can't (accessibility skipping, for example), and there are things that TypeBuilder
can do that DynamicMethod
can't (implement interfaces, declare and use fields, etc); if you don't need those things, Expression.Compile()
is a pretty good way of avoiding having to learn low-level ref-emit, which is very easy to get wrong (and invalid IL usually kills the runtime)Expression
can choose to spoof the emit, by actually running via an AST interpreter instead, on runtimes that do not allow ref-emit; Compile()
returns an entry-point to this interpreter, instead of a delegate to a dynamically compiled method; this option is not available if you use TypeBuilder