Search code examples
c#asp.netexpression-trees

Expression Tree


My understanding of expression trees is :

Expression trees are in-memory representation of expression-like arithmetic or boolean expressions. The expressions are stored into a parsed tree, so we can easily translate into any other language.

Linq-to-SQL uses expression trees. Normally in a Linq-to-SQL query the compiler translates it into parsed expression trees. These are passed to SQL Server as T-SQL Statements. The SQL server executes the T-SQL query and sends the result back. This is why when you execute Linq-to-SQL you get IQueryable<T> not IEnumerable<T>; because IQueryable contains

public IQueryable : IEnumerable
{
   Type Element {get;}
   Expression Expression {get;}
   IQueryableProvider Provider {get;}
}

Questions :

  1. Microsoft uses Expression trees in LINQ-to-SQL. What are the different ways I can use expression trees to boost my code?

  2. Apart from LINQ-to-SQL, Linq to amazon, who uses expression trees in their applications?

  3. Linq-to-Object returns IEnumerable, Linq-to-SQL returns IQueryable, What does LINQ-to-XML return?


Solution

  • Expression trees offer a way to inspect some piece of code before it is actually compiled, at runtime.

    You can do exactly two things with an expression tree:

    • Compile it into a delegate, using Expression.Compile, or
    • Visit the tree nodes and generate something else from it (i.e. a SQL statement).

    Expression trees are cool, but the odds of them actually having any direct usefulness for a typical website or enterprise app are remote. You would only use them when you (a) want to generate a different type of code from C# source at runtime, or (b) want to use Reflection but provide some measure of compile-time safety.

    If you are working on reusable libraries - DI frameworks, AOP frameworks, MVC/MVP/MVVM frameworks, ORM frameworks, and so on, or trying to extend one of these frameworks (including Linq-to-XYZ), then you will likely find a use for expression trees (such as the Linq to SQL batch update extension), although it's hard to discuss specific examples because it would depend entirely on the design of such a framework.

    If you're not building these sorts of tools then expression trees aren't much more than a curiosity. Great to learn about of course - but don't be disappointed if you don't find too many practical uses for them.

    A few examples of libraries that use expression trees:

    ...That should give you an idea of the kind of projects that make serious use of expression trees. So if you're building your own runtime environment or MVC, you definitely want to learn everything you can. ;)