Expression Tree Basic

suggest change

Expression trees represent code in a tree-like data structure, where each node is an expression.

Expression trees enable dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries. You can compile and run code represented by expression trees.

These are also used in the dynamic language run-time (DLR) to provide interoperability between dynamic languages and the .NET Framework and to enable compiler writers to emit expression trees instead of Microsoft intermediate language (MSIL).

Expression trees can be created in two ways:

  1. From a lambda expression.
  2. Manually, with the System.Linq.Expressions namespace.

Expression Trees from Lambda Expressions

When a lambda expression is assigned to an Expression<TDelegate> variable, the compiler emits code that builds an expression tree for that lambda.

The following example has the compiler build a tree for num => num < 5.

Expression<Func<int, bool>> lambda = num => num < 5;

Expression Trees by Using the API

Expression trees are also built with the Expression class. Its static factory methods create nodes of specific types.

Two of those node types are:

  1. ParameterExpression
  2. MethodCallExpression

The following code example shows how to create an expression tree that represents the lambda expression num => num < 5 by using the API.

ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);
Expression<Func<int, bool>> lambda1 = Expression.Lambda<Func<int, bool>>(numLessThanFive,new ParameterExpression[] { numParam });

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents