Sean Chambers
Sean Chambers

Reputation: 8680

What are some instances in which expression trees are useful?

I completely understand the concept of expression trees, but I am having a hard time trying to find situations in which they are useful. Is there a specific instance in which expression trees can be applied? Or is it only useful as a transport mechanism for code? I feel like I am missing something here. Thanks!

Upvotes: 11

Views: 1560

Answers (3)

Keith
Keith

Reputation: 155662

Expression trees are useful when you need to access function logic in order to alter or reapply it in some way.

Linq to SQL is a good example:

//a linq to sql statement
var recs (
    from rec in LinqDataContext.Table
    where rec.IntField > 5
    select rec );

If we didn't have expression trees this statement would have to return all the records, and then apply the C# where logic to each.

With expression trees that where rec.IntField > 5 can be parsed into SQL:

--SQL statment executed
select *
from [table]
where [table].[IntField] > 5

Upvotes: 4

Konrad Rudolph
Konrad Rudolph

Reputation: 545568

Or is it only useful as a transport mechanism for code?

It's useful as an execution mechanism for code. Using the interpreter pattern, expression trees can directly be interpreted. This is useful because it's very easy and fast to implement. Such interpreters are ubiquitous and used even in cases that don't seem to “interpret” anything, e.g. for printing nested structures.

Upvotes: 6

Fredrik Kalseth
Fredrik Kalseth

Reputation: 14214

Some unit test mocking frameworks make use of expression trees in order to set up strongly typed expectations/verifications. Ie:

myMock.Verify(m => m.SomeMethod(someObject)); // tells moq to verify that the method
                                              // SomeMethod was called with 
                                              // someObject as the argument

Here, the expression is never actually executed, but the expression itself holds the interesting information. The alternative without expression trees would be

myMock.Verify("SomeMethod", someObject) // we've lost the strong typing

Upvotes: 7

Related Questions