Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the point of Expression Trees?

Ok, I just don't get it.

I've read about as much as I can on the subject without knowing what it's all about:

  • Why use Expression Trees?
  • What's a real-world example of when and how I'd use them?
  • What overall benefit(s) are there in using them?
like image 445
IAmAN00B Avatar asked Jul 28 '10 20:07

IAmAN00B


2 Answers

Expression trees API originally was written to enable creation of custom LINQ providers. Basically, if you use LINQ to Objects you don't deal with Expression Trees. But if you work with LINQ to SQL then the LINQ provider works with Expression Trees.

In .Net 4.0 Expression Trees API was extended and is heavily used by DLR. So, if you are going to let's say add a new dynamic langauge to the .NET, you'll need it.

As it often happens, people found more ways to use expression trees. Sometimes you can use ET to get more information about objects instead of reflection. In .NET 4 you can also use them to generate dynamic methods. But remember that these are more like advanced tricks rather than recommended scenarios.

Here are some links you can take a look at:

Expression Tree Basics

Getting Information About Objects, Types, and Members with Expression Trees

Generating Dynamic Methods with Expression Trees in Visual Studio 2010

like image 120
Alexandra Rusina Avatar answered Oct 04 '22 17:10

Alexandra Rusina


An expression tree is essencially a parsed bit of code handled to you as data. Your program can then interprete that data as you like at run-time. This allows you to interpret code in light of your business logic.

Say you needed to define business rules. You can define a syntax for them based on C#, and then have the new rule written directly in the source code. By accepting it into you engine as an Expression Tree, the tedious work of parsing, syntax checking and type checking is already done for you. You just have to run through the tree and apply the rule.

like image 25
James Curran Avatar answered Oct 04 '22 18:10

James Curran