Change expression delegate body at runtime?

.net .net-4.0 c# expression-trees

Question

I have this code which produce a delegate which multiply myNumber by 5

ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numMultiply = Expression.Multiply(numParam,five);

Lets create the delegate :

Expression<Func<int, int>> lambda1 =
    Expression.Lambda<Func<int, int>>(
        numMultiply,
        new ParameterExpression[] { numParam });
Console.Write(lambda1.Compile()(4));

now let's say I want to change this expression tree to Add instead of Multiply
here is the new line :

BinaryExpression numAdd = Expression.Add(numParam,five);

But how can I change the lambda1 so that it will now will use numAdd instead of multiply ?

Accepted Answer

You just build a new one, and compile it.

Expression<Func<int, int>> lambda1 =
     Expression.Lambda<Func<int, int>>(
         numAdd,
         new ParameterExpression[] { numParam });

From the MSDN page:

Expression trees should be immutable. This means that if you want to modify an expression tree, you must construct a new expression tree by copying the existing one and replacing nodes in it. You can use an expression tree visitor to traverse the existing expression tree.

The "should be" phrase is a little odd but when you look at the API you will see that all relevant properties (Body, Left, Right) are read-only.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why