What is the benefit of Expression Trees?

.net expression-trees


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

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.

Popular Answer

Expression trees are using widely in LINQ to SQL, Entity Framework, ASP.NET MVC's HTML extensions where the runtime needs to interpret the expression in a different way (LINQ to SQL and EF: to create SQL, MVC: to determine the selected property or field).

If you don't need that can of re-interpretation of a C#/VB expression you don't need to use Expression trees.

(There are plenty of things in .NET you'll not use most of the time: eg. ServiceBase only applies if writing a service, WPF is not relevant to a web app.)

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