Expression trees purpose:
Expression tree must be
compiled before it can be used. This is because expression tree is
actually a data structure, not compiled code. Why? Because this code
is expected to be used across wire, or – in other words – in other
processes (running possibly on other computers).
From: http://geekswithblogs.net/Martinez/archive/2009/06/29/understanding-expression-trees.aspx
What is the difference between ‘Data Structure’ and ‘compiled code’; How does comipled code looks like in C# ?! By this article I understand that every line that does not contain Array or List is compiled code (Like: "Human H1=new Human(18);").
Please dont expain me what are Expression trees with examples, I want a clear answer about this question.
Thank you for your time
You cannot execute an expression tree without compiling it first because expression trees serve a different purpose: they work as flexible blueprints for executable code, rather than being the the executable code itself (with is rather inflexible).
An expression tree is a data structure that describes code (compiled or not) at an abstraction level that is higher than the code itself. Unlike code, the data structure can be manipulated to make a different structure that describes some other piece of code. Unlike the data structure, the code can be evaluated to produce a result.
Consider this example:
It shows an expression
exprbeing created, describing a simple expression treea+b. At this point, we have a tree-like data structure with three nodes – two nodes representing parameters, and one node representing addition. We can do lots of things with the expression tree, such as examining its content, finding its return type, and so on. We can even manipulate its structure to make other expressions based on it: for example, we could add a third parameter, and makea+b+c, like this:One thing we cannot do, however, is pass it two integer values and obtain their sum: expression trees do not provide methods for evaluating them. In order to do that, you need real code, not a description of code.
Expression trees provide a way to convert descriptions of code into code by way of compiling them. Once you make an expression tree into lambda and call the
Compile()method on it, you get back a compiled CIL code that looks like this:This code can be passed two values for evaluation, and it will return the sum to you. However, some information is lost in translation: specifically, the names of parameters
aandbare no longer there in the compiled code: they are not necessary to perform calculations, so they have been eliminated.