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:
- 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™.
- 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.