Bit Curious to understand Expression Tree in .NET

c# expression expression-trees

Question

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.

Accepted Answer

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;

Expert Answer

Expression is a versatile way of expressing code operations as an object model. This is extended much more in 4.0, but this is an area I use a lot; I have some blog points here, or another attempt at explaining it all on InfoQ. I've also presented this subject a few times - perhaps try the download here (but it won't make as much sense without the words; sorry).

I'll be honest; it isn't a simple subject - but it is hugely powerful when you grok it. From the above, I'd probably start with the InfoQ.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why