Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical use of expression trees [closed]

Expression trees are a nice feature, but what are its practical uses? Can they be used for some sort of code generation or metaprogramming or some such?

like image 921
Dmitri Nesteruk Avatar asked Dec 31 '08 14:12

Dmitri Nesteruk


People also ask

What are expression trees used for?

Expression Trees represent code as a structure that you can examine, modify, or execute. These tools give you the power to manipulate code during run time. You can write code that examines running algorithms, or injects new capabilities.

What is an expression tree give an example?

The binary expression tree is a binary tree whose leaves are operands, such as constants or variable names, and the other nodes contain operators. For example, the postfix notation a b + c d e + * * results in the following expression tree.

What do the leaves of an expression tree represent?

The leaves of an expression tree always contain? Explanation: The leaves of an expression tree always contain the result of a given expression (i.e.) operands.

What is meant by expression tree?

An expression tree is a representation of expressions arranged in a tree-like data structure. In other words, it is a tree with leaves as operands of the expression and nodes contain the operators. Similar to other data structures, data interaction is also possible in an expression tree.


2 Answers

As Jon notes, I use them to provide generic operators with .NET 3.5. I also use them (again in MiscUtil) to provide fast access to non-default constructors (you can't use Delegate.CreateDelegate with constructors, but Expression works fine).

Other uses of manually created expression trees:

  • object cloning
  • dynamic LINQ sorting
  • as a compiler

But really, Expression is a very versatile way of writing any dynamic code. Much simpler than Reflection.Emit, and for my money, simpler to understand than CodeDOM. And in .NET 4.0, you have even more options available. I show the fundamentals of writing code via Expression on my blog.

like image 71
Marc Gravell Avatar answered Sep 22 '22 06:09

Marc Gravell


Marc Gravell has used them to great effect in MiscUtil to implement generic operators.

like image 38
Jon Skeet Avatar answered Sep 23 '22 06:09

Jon Skeet