home screen

Search



Number Of Result : 0

Result :


Wednesday, January 21, 2009

BinaryExpression With Operators

//example creates expression tree of x *x
public static void CreatingExpressionTree()
{
//You first start off with a parameter expression of type int.
ParameterExpression parameter1 = expression.Expression.Parameter(typeof(int), "x");

ParameterExpression parameter2 = expression.Expression.Parameter(typeof(int), "y");

//The next step is to build the body of lambda expressions which happens to be a binary expression. The body consists of a multiply operator to the same parameter expression.
BinaryExpression multiply = expression.Expression.Multiply(parameter1, parameter2);

//The final step is to build the lambda expression which combines the body with the parameter as follows:
Expression<Func<int, int , int>> square = expression.Expression.Lambda<Func<int,int, int>>(
multiply, parameter1 , parameter2);
//The last step converts the expression to delegate and executes the delegate as follows:
Func<int, int , int> lambda = square.Compile();
//Console.WriteLine(lambda(5));
MessageBox.Show(lambda(10 , 14).ToString());
}

public static void CreatingAnExpressionFromAnotherExpression()
{

//We start off with a lambda expression which returns a square:
Expression<Func<int, int>> square = x => x * x;

//Next we generate the body of the new lambda expression by using the body of the first lambda expression and adding a constant of 2 to it and assigning it to the binary expression:
BinaryExpression squareplus2 = expression.Expression.Add(square.Body,
expression.Expression.Constant(2));

//In the last step, we generate the new lambda expression by combining the body with the parameters from the first lambda expression. The important point which I discovered in the statement below is that, a parameter's reference needs to be exactly the same from the first lambda expression which is square.Parameters. You cannot create a new instance of parameters collection which results in a runtime error.
Expression<Func<int, int>> expr = expression.Expression.Lambda<Func<int, int>>(squareplus2,
square.Parameters);

Func<int, int> compile = expr.Compile();

MessageBox.Show(compile(10).ToString());
//result = 10 * 10 + 2 = 102
}

No comments: