During working over Camlex.NET project in order to provide support of non-constant expressions we needed evaluate sub-expressions in runtime as results of these expression are required to construct CAML query. I.e. suppose that we have expression of the following general schema:
Here x is a parameter of lambda expression, Type – type allowed for casting in Camlex, and expr1 and expr2 – some expressions which should be evaluated in runtime. Expr1 and expr2 can be for example variables, method calls, ternary operator, etc.. For example:
The expression above will be translated in the following CAML:
As shown here results of expr1 and expr2 (“Title” and “Camlex”) are used for CAML query creation. So how do we evaluate exp1 and expr2:
First of all we need to represent expr1 and expr2 as Expression object using expression trees. In order to evaluate this expression we need to convert it to lambda expression () => expr which returns “object” type. Here little trick is made: we construct new unary expression which represents casting to object:
Whatever actual expression was in expr1 or expr2, now the final operation for these expressions will be casting to object: (object)expr1 (of course it is not so efficiency if expressions return value type because of boxing/unboxing, but it will allow us to invoke expression in runtime). I.e. we added new operation to existing expressions.
Now it is not so hard to evaluate this expression. We create lambda expression: () => (object)expr1 with the following code: