What is the best resource for learning C# expression trees in depth?

Chapter 11 (Inside Expression Trees) and chapter 12 (Extending Linq) of Programming Microsoft Linq (ISBN 13: 978-0-7356-2400-9 or ISBN 10: 0-7356-2400-3) has been invaluable for me. I haven't read Jons book, but he is a quality guy and explains things well, so I assume that his coverage would also be good.

Another great resource is Bart De Smet's blog

Also, keep your eye on MSDN, the sample code for building a Simple Linq to Database (by Pedram Rezaei) is about to get about 40 pages of Doco explaining it.

A really, really useful resource for Expression Tree's in fact I would regard it as a must have is the Expression Tree Visualiser debugging tool.

You should also learn as much as you can about Expression Tree Visitors, there is a pretty good base class inplementation here.

Here is some sample code derived from that Visitor class to do some debugging (I based this on some sample code in the book I mentioned) the prependIndent method call is just an extension method on a string to put a "--" at each indent level.

  internal class DebugDisplayTree : ExpressionVisitor
  {
    private int indentLevel = 0;

    protected override System.Linq.Expressions.Expression Visit(Expression exp)
    {
      if (exp != null)
      {
        Trace.WriteLine(string.Format("{0} : {1} ", exp.NodeType, exp.GetType().ToString()).PrependIndent(indentLevel));
      }
      indentLevel++;
      Expression result = base.Visit(exp);
      indentLevel--;
      return result;
    }
    ...

I don't claim them to be comprehensive, but I have a number of Expression posts on my blog. If you are UK based, I will also be presenting a session on Expression at DDD South West in May (and last night, but too late ;-p). I could post the slide deck and some of the links from related articles, if you want... unfortunately, a pptx intended to be spoken rarely makes sensible standalone reading.

Some other reading (not from the blog):

  • Jason Bock: genetic programming with Expression
  • (me again): generic operators with Expression
  • (and again, on InfoQ) Expression as a Compiler

(and a whole load of posts here and on microsoft.public.dotnet.languages.csharp - try searching for: +expression -regex -"regular expression"


Learn Scheme. Expressions use the same principles as lambda calculus, and hence will give you some better insight.

Alternatively, you can look at the DLR, which is a similar but much less elegant.