Search code examples
c#variablesexpression-treescallstack

Share variables between expression trees


I'm wondering if there is a flexible and efficient way to share variables between multiple compiled expression trees?

I am writing an expression parser. At the moment, I am able to execute single line statements. Using Expression.Block, it is possible to build arbitrary large expression trees with multiple variables. However, they become very difficult to debug as you have no control on what happens inside the compiled lambda (e.g. no possibility to set breakpoints or watches). Therefore I would like to split this single expression tree into multiple ones, all operating on on the same variables (passed in as a parameter of the lambda).

The simplest solution I can think of is using an array of objects as parameter to pass into the lambda. However, in this case I have to convert/box/unbox the values every time I am accessing them. Is there a way to simulate a "call stack" where the variables are directly aligned as their native representation in memory?


Solution

  • You should create your own class (using TypeBuilder) with a field for each member you want.