Practical use of expression trees

Dmitri Nesteruk picture Dmitri Nesteruk · Dec 31, 2008 · Viewed 25.9k times · Source

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?

Answer

Marc Gravell picture Marc Gravell · Dec 31, 2008

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:

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.