C# language feature:
applies to
benefit
how to use
more info
example:
void Use_of_Expression_Tree() {
// Create and expression tree that subtracts two integers
// 1) Create the expression
ParameterExpression openandLeft = Expression.Parameter(typeof(int), "openandLeft");
ParameterExpression operandRight = Expression.Parameter(typeof(int), "operandRight");
ParameterExpression[] parameters = new ParameterExpression[] { openandLeft, operandRight };
BinaryExpression body = GetBinaryMathOperatorExpression('-', openandLeft, operandRight); //Create the expression body
Expression<Func<int, int, int>> expression = Expression.Lambda<Func<int, int, int>>(body, parameters); //Create the expression
Func<int, int, int> compiledExpression = expression.Compile(); // Compile the expression
// 2) Execute the expression.
int result = compiledExpression(7, 4); //returns 3
// alternatively create and execute an expression tree that adds to integers
body = GetBinaryMathOperatorExpression('+', openandLeft, operandRight);
expression = Expression.Lambda<Func<int, int, int>>(body, parameters); //Create the expression
compiledExpression = expression.Compile(); // Compile the expression
// Execute the expression.
result = compiledExpression(7, 4); //returns 11
// A potential use of expression trees is to allow a user specified expression for a calculated field/output
}
BinaryExpression GetBinaryMathOperatorExpression(char mathoperator, ParameterExpression opL, ParameterExpression opR)
{
switch (mathoperator) {
case('+'):return Expression.Add(opL, opR);
case ('-'): return Expression.Subtract(opL, opR);
default:
throw new NotImplementedException();
}
}