How can you create Expression Trees?

You can create expression trees by using following two ways:

  1. Using Expression Lambda – The easiest way to generate an expression tree is to create an instance of the Expression<T> type, where T is a delegate type, and assign a lambda expression to this instance.
    // Create an expression using expression lambda
    Expression < Func < int, int, int >> expression = (num1, num2) = > num1 + num2;
    // Compile the expression
    Func < int, int, int > compiledExpression = expression.Compile();
    // Execute the expression.
    int result = compiledExpression(3, 4); //return 7

    In this example, the C# compiler generates the expression tree from the provided lambda expression. This looks much more complicated, but this is what actually happens when you supply a lambda expression to an expression tree.
    The structure of above expression trees will be like as:

  2. Using Expression Tree API – Expression class is used to create expression trees by using the API. In .NET Framework 4, the expression trees API also supports assignments and control flow expressions such as loops, conditional blocks, and try-catch blocks. By using the API, you can create expression trees that are more complex than those that can be created from lambda expressions. Using API, above code can be re-written as:
    //Create the expression parameters
    ParameterExpression num1 = Expression.Parameter(typeof(int), "num1");
    ParameterExpression num2 = Expression.Parameter(typeof(int), "num2");
    //Create the expression parameters
    ParameterExpression[] parameters = new ParameterExpression[] {
    	num1, num2
    };
    //Create the expression body
    BinaryExpression body = Expression.Add(num1, num2);
    //Create the expression
    Expression < Func < int, int, int >> expression = Expression.Lambda < Func < int, int, int >> (body, parameters);
    // Compile the expression
    Func < int, int, int > compiledExpression = expression.Compile();
    // Execute the expression
    int result = compiledExpression(3, 4); //return 7
Tagged , . Bookmark the permalink.

Leave a Reply