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

Donny picture Donny · Apr 4, 2012 · Viewed 37.4k times · Source

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.

Answer

Roy Dictus picture Roy Dictus · Apr 4, 2012

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