Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Expression Trees

I'm not sure why I'm reading up on Expression Trees but I am. As such, I have no understanding of the object, or where or how it's used.

Reading other questions here, such as What are Expression Trees and how do you use them and why would you use them? (and the links they cite), I now understand the Expression Tree a little bit better but, I'm still lost as to why it is used.

The only example I've seen as to why, is things like Linq to SQL - but when you investigate it a little more, it appears to actually be more about it's use with IQueryable<T> interface.

Are expression trees only useful (used) in conjunction with IQueryable interface?

like image 736
MyDaftQuestions Avatar asked Jul 16 '26 09:07

MyDaftQuestions


1 Answers

It's a bit of a tautology, but the answer is "Whenever you need to understand an expression".

A common question I have seen from junior developers is "What is the difference between Func<T> and Expression<Func<T>>?" For most, the latter requires you call Compile() on the expression to get the function it represents, but otherwise they appear to do the same job.

Expression trees let the compiler embed what would normally be instructions as an explorable tree of expressions. If you are writing something that needs to understand not just the result of a function, but how a caller constructed their function, expression trees can capture this for you.

You have to need to know how the expression is composed before the difference becomes relevant.

I've only seen expressions used in two ways:

  1. Creating a LINQ provider (like LINQ-to-SQL) to interpret an expression and convert it into another language. As you already know, this involves implementing IQueryable and is a Big Deal™.
  2. Capturing property accessors from objects (like Razor HTML Helpers) so the value can not only be accessed, but also the name of the property can be used to generate things (like HTML field names).

The common task tends to be some sort of translation to another language. In the case of LINQ providers, it's a direct translation of a query into another query language. In the case of Razor, it's conversion of a property into an HTML field.

like image 112
Paul Turner Avatar answered Jul 18 '26 02:07

Paul Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!