Search code examples
c#.netlinqexpression-trees

What are Expression Trees, how do you use them, and why would you use them?


I just came across the concept of expression trees which I have heard multiple times. I just want to understand what is meant by an expression tree and its purpose.

I would love it if someone could also direct me to simple explanations and samples of use.


Solution

  • An Expression Tree is a data structure that contains Expressions, which is basically code. So it is a tree structure that represents a calculation you may make in code. These pieces of code can then be executed by "running" the expression tree over a set of data.

    A great thing about expression trees is that you can build them up in code; that is, you build executable code (or a sequence of steps) in code. You can also modify the code before you execute it by replacing expressions by other expressions.

    An Expression is then a function delegate, such as (int x => return x * x).

    See also http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx