Trying to understand what an expression tree is

Both fragments below the product of the same yield. I understand how Func encapsulates a method with a single parameter and returns a bool value. And you can either assign it a method, an anonymous method, or a lambda expression.

Func<int, bool> deleg = i => i < 5; Console.WriteLine("deleg(4) = {0}", deleg(4)); 

The following are expression trees that I do not yet fully understand. Why should I do this? Is it more flexible, what advantage does it give me?

 System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5; Func<int, bool> deleg2 = expr.Compile(); Console.WriteLine("deleg2(4) = {0}", deleg2(4)); 
+4
source share
4 answers

Basically, the expression tree is the body of the lambda expression, which allows

  • inherit the expression (see what it says)
  • manipulate the expression (simplify, expand (for example, add new functionality or change to work with various elements).

After the Compile() expression, this is just another delegate that you can only call, not check or modify.

Whenever you want

  • dynamically create expressions (I mean: build, not select)
  • dynamically work with expressions

Function<> types are insufficient.

+5
source

The point of expression trees is that you can do more with them than just compile them for a function. You can check, modify, and compile them into something other than .net functions.

For example, Linq2SQL compiles expression trees into SQL code. You could not do this with a simple .net function.

+1
source

In the first example, you simply "hardcoded" the body of the function and assigned it to the delegate.

In your second example, assignment creates an expression tree, which is an object model that overrides your code in the data structure in memory.

The advantage is that you can modify and validate this data structure.

LINQ2SQL, for example, uses this method to translate your expressions into another language called SQL.

+1
source

Expression trees are regular in-memory data structures that can be skipped programmatically, and the result of such a crawl may be something like a query that you want to send to the database. Read more in the ExpressionVisitor class to find out how.

On the other hand, a compiled function is nothing more than a sequence of CIL code. You can still check this programmatically, but you are not checking the definition, but rather the compiler output.

0
source

All Articles