|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
How to: Execute Expression Trees
This topic shows you how to execute an expression tree. Executing an expression tree may return a value, or it may just perform an action such as calling a method.
Only expression trees that represent lambda expressions can be executed. Expression trees that represent lambda expressions are of type LambdaExpression or Expression<TDelegate>. To execute these expression trees, call the Compile method to create an executable delegate, and then invoke the delegate.
If the type of the delegate is not known, that is, the lambda expression is of type LambdaExpression and not Expression<TDelegate>, you must call the DynamicInvoke method on the delegate instead of invoking it directly.
If an expression tree does not represent a lambda expression, you can create a new lambda expression that has the original expression tree as its body, by calling the Lambda<TDelegate>(Expression, IEnumerable<ParameterExpression>) method. Then, you can execute the lambda expression as described earlier in this section.
The following code example demonstrates how to execute an expression tree that represents raising a number to a power by creating a lambda expression and executing it. The result, which represents the number raised to the power, is displayed.
// The expression tree to execute. BinaryExpression be = Expression.Power(Expression.Constant(2D), Expression.Constant(3D)); // Create a lambda expression. Expression<Func<double>> le = Expression.Lambda<Func<double>>(be); // Compile the lambda expression. Func<double> compiledExpression = le.Compile(); // Execute the lambda expression. double result = compiledExpression(); // Display the result. Console.WriteLine(result); // This code produces the following output: // 8