What are the advantages of using Expression Trees?

.net expression-trees

Question

While developing the applications using .Net language, I am not getting the use or benefit of the expression tree? Is it really necessary ?

1
4
6/14/2012 7:56:55 AM

Expert Answer

An expression tree allows you to express your code in regular C#, but to deconstruct that, inspect it, and interpret it. For example, you might interpret it by writing an equivalent TSQL string (example: LINQ-to-SQL or Entity Framework), or a web-service query (astoria). You might interpret it as an RPC call (I've written an expression-based RPC layer).

To repeat my "Explaining Expression" blog entry:

  • The delegate version (Func<int,int,bool>) is the beligerant manager; "I need you to give me a way to get from 2 integers to a bool; I don't care how - when I'm ready, I'll ask you - and you can tell me the answer".
  • The expression version (Expr<Func<int,int,bool>>) is the dutiful analyst; "I need you to explain to me - if I gave you 2 integers, how would you go about giving me a bool?"

If you have the expression, you can either call Compile() to form a delegate (to do it exactly as explained), or you can unpick it and do something similar based on what steps they took.


Another view on Expression is that it can act as a simplified version of ILGenerator - but still be pretty versatile. Very useful for meta-programming. Here's an article exploring that approach.

4
4/29/2011 10:35:59 AM

Popular Answer

If you do not get benefits of the expression trees then I think:
- either you do not have any code which requires expression trees
- or you do not see places where your code can be improved by using expression trees.

First point is Ok, most of the applications I've developed had no place for expression trees. And in order to deal with second point you just have to know what are the expression trees, how do they work and what they can/cannot do.

Expression trees are usually used when you need to have an ability to traverse some code model, for example in order to generate some other code based on this one. As already mentioned this approach is used in Linq-to-SQL for example. Another not out-of-box example might be an application where you need to have an object's property as a first class citizen object in your application, i.e. you need to be able to pass the property as an instance of some class. The same can be done with reflection but expression trees allow making such code less stringly typed.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow