CompileToMethod does not support instance methods, constructors, dynamicmethods


LambdaExpression.CompileToMethod doesn't support instance methods, constructors, or dynamic methods. It should take a MethodBase as the first argument, and allow any kind of ConstructorBuilder/MethodBuilder/DynamicMethod. Also, it shouldn't clobber the parameters/return type of the MethodBuilder (this change is necessary because I don't think we can modify parameters/return type of a DynamicMethod after creation).
Closed Feb 9, 2009 at 5:37 PM by billchi


billchi wrote Feb 18, 2009 at 4:49 PM

After much investigation, it turns out this is by won't fix for CLR 4.0

You can't use expression trees to model instance methods or constructors. First problem: you can't create the "this" parameter, because all you have in hand is a TypeBuilder, but that is not the final type. We can create a delegate with the TypeBuilder, but CLR won't let us create a LambdaExpression with that delegate (because the type is not finished). You can workaround that by making the "this" parameter be of type object, then you end up with meaningless casts. Worse, calls to your own methods don't work, because MethodBuilder doesn't implement enough of reflection for expression trees to do their normal sanity checks.

DynamicMethods run into their own problems. When emitting into a DynamicMethod, we can't add our Closure argument to the signature of the DynamicMethod. Without a closure, DynamicMethods run into some serious limiations:
  • They can't have nested lambdas at all (due to a CLR limitation: can't ldftn to a DynamicMethod).
  • Some things that are O(1) or amortized O(1) become O(N), such as RuntimeVariables and Switch on strings. This is really sneaky for the user who won't expect things to suddenly be slower.
This needs work we plan for ETs v3, and the design around the support will likely change.


justinc wrote Aug 2, 2009 at 3:30 PM

Well how does IronPython generate Types? Does it not use similar expression builders to make methods? Does it not create Types at all? How can we simulate dynamic Type creation in a way similar to IronPython?

wrote Feb 21, 2013 at 11:41 PM

wrote May 16, 2013 at 11:29 AM