Search code examples
c#expressionexpression-trees

Bit Curious to understand Expression Tree in .NET


I have read several articles and several stackoverflow.com posts about expression tree. It is beating my brain to understand.

Questions:

1) Like DOM (Document Object Model), it is an in-memory representation of logic?

2) Somebody explained it is a mechanism to translate an executable code into data, using it we can produce a data structure representing the code.

Does it mean, expression trees are used to design a user defined pattern?

3) Most of the Examples show Expression tree in conjunction with Func<> delegate or other delegates, So using delegate and other programming construct can’t we achieve the same thing as expression tree serves.

Beginners-understandable explanation is highly appreciated.


Solution

  • Expression tree represent a syntax tree of a single expression.

    Each node of tree represent some constant, object member reference or operation.

    E.g. for expression 2 + 3 we can build and expression tree:

    Expression.MakeBinary(
        ExpressionType.Add,
        Expression.Constant(2),
        Expression.Constant(3));
    

    The most important of such trees is Expression which allows to write expression in nice readable form reminding lambda functions of signature matching TDelegate. Here's ex

    Expression<Func<int>> sum = () => 2 + 3; // much nicer, eh?
    

    But Expression is not delegate, since it couldn't be executed directly.

    Instead it can be traversed e.g. with visitor object to build some executable representation. Examples could be delegate build with Expression.Compile() or SQL query built from LINQ query using CompiledQuery.Compile() etc.

    Another useful application of expression trees is using them to represent members of objects that otherwise would require usage of Reflection. Reflection uses strings to represent member names and makes no checks at compile time. Expression trees are checked, so a little less errors could be made.

    PropertyInfo prop1 = typeof(MyClass).GetProperty("Value");
    
    Expression<Func<MyClass, int>> expr = mc => mc.Value;
    PropertyInfo prop2 = (mc.Body as MemberExpression).Member as PropertyInfo;