Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some instances in which expression trees are useful?

Tags:

c#

expression

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!

like image 643
Sean Chambers Avatar asked Aug 26 '08 10:08

Sean Chambers


People also ask

What are expression trees used for?

Expression Trees represent code as a structure that you can examine, modify, or execute. These tools give you the power to manipulate code during run time. You can write code that examines running algorithms, or injects new capabilities.

What are the advantages of expression tree?

Expression trees allow you to build code dynamically at runtime instead of statically typing it in the IDE and using a compiler. They are well explained in the documentation.

What is an expression tree give an example?

Each node in an expression tree is an expression. For example, an expression tree can be used to represent mathematical formula x < y where x, < and y will be represented as an expression and arranged in the tree like structure. Expression tree is an in-memory representation of a lambda expression.

What is expression trees and how they used in LINQ?

Expression Trees was first introduced in C# 3.0 (Visual Studio 2008), where they were mainly used by LINQ providers. Expression trees represent code in a tree-like format, where each node is an expression (for example, a method call or a binary operation such as x < y).


2 Answers

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
like image 137
Fredrik Kalseth Avatar answered Oct 20 '22 00:10

Fredrik Kalseth


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.

like image 41
Konrad Rudolph Avatar answered Oct 20 '22 00:10

Konrad Rudolph