C 30 Expression Tree Again part 2

In the preceding post I showed that a lambda expression can be converted by the compiler in an object of type Expression that actually models the expression tree. With this post we can begin to have more fun, first of all I modified the visitor to show the exact tree of the expression. Here is a screenshot

image

As you can see the structure of the lambda is more clear, the original lambda contains an Add Expression that in turns contains two parameter expression. The lambda has a collection of parameters that can be inspected at runtime, I simply show them in a listview and permit to the user to set a value. When you set values for parameters you can press the Execute button and “voilà “, the expression is executed. The code to execute the function is the following.

1
2
3
4
5
6
7
8
9
LambdaExpression ex = treeView1.SelectedNode.Tag as LambdaExpression;
if (ex == null) return;
Delegate d = ex.Compile();
Object[] parameters = new Object[lstParameters.Items.Count];
for (Int32 I = 0; I < ex.Parameters.Count; ++I)
{
    parameters[I] = lstParameters.Items[I].SubItems[1].Tag;
}
txtResult.Text = d.DynamicInvoke(parameters).ToString();

I simply compile the LambdaExpression calling Compile() method, it returns a Delegate, then I retrieve the value of the parameters, that are stored in tag property of the listview items, I create the Object[] array of parameters and then call DynamicInvoke on the Delegate….the game is done.

Welcome into the marvelous world of Expression Tree ;)

Alk.

Download the Example code