InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

Get a Grasp on Expression Trees

Posted by Hartmut Wilms on Feb 06, 2008

Sections
Development
Topics
.NET Framework ,
.NET
Tags
LINQ ,
Functional Programming

Developers familiar with functional programming languages might not need an explanation as to why expression trees are useful. For the rest of us expression trees are the most striking concept of all the new features in C# 3.0 or VB 9.0.

Charlie Calvert explains the Expression Tree Basics. He starts by describing the syntax and shows how to visualize expression trees with the help of the ExpressionTreeVisualizer that ships with the Visual Studio 2008 samples.

Expression trees are related to lambda expressions, which are the logical next step in the line of delegates and anonymous delegates.  In his article on expression trees Ian Griffiths gives a great introduction to lambda expressions and their relation to expression trees. As Ian points out "lambdas don't appear to offer anything I didn't already have with anonymous methods besides a different syntax. However, they turn out to be able to do something that anonymous methods cannot":

Func<int, bool> nonExprLambda = x => (x & 1) == 0;
Expression<Func<int, bool>> exprLambda = x => (x & 1) == 0;

[...]

The second line is more interesting. This takes that Func delegate, and uses it as the type parameter for a generic type called Expression. It then proceeds to initialize it in exactly the same way, so you'd think it was doing much the same thing. But it turns out that the compiler knows about this Expression type, and behaves differently. Rather than compiling the lambda into IL that evaluates the expression, it generates IL that constructs a tree of objects representing the expression.

Charlie delves into the Expression details:

There are four properties in the Expression<TDelegate> class:

  • Body: Retrieve the body of the expression.
  • Parameters: Retrieve the parameters of the lambda expression.
  • NodeType: Gets the ExpressionType for some node in the tree. This is an enumeration of 45 different values, representing all the different possible types of expression nodes, such as those that return constants, those that return parameters, those that decide whether one value is less than another (<), those that decide if one is greater than another (>), those that add values together (+), etc.
  • Type: Gets the static type of the expression. In this case, the expression is of type Func<int, int, int>.

As almost all of the new features in C# 3.0 and VB 9.0 expression trees play a key role in "LINQ, and particularly in LINQ to SQL":

var query = from c in db.Customers
where c.City == "Nantes"
 select new { c.City, c.CompanyName };

LINQ expressions return an IQueryable. IQueryable contains an expression tree, which represents the LINQ query. At the moment the query is created, no SQL statement is issued to the database. The SQL statement is created and executed when your code iterates the IQueryable object. This concept is called deferred execution.

Charlie Calvert explains the use of this approach:

Because the query comes to the compiler encapsulated in such an abstract data structure, the compiler is free to interpret it in almost any way it wants. It is not forced to execute the query in a particular order, or in a particular way. Instead, it can analyze the expression tree, discover what you want done, and then decide how to do it. At least in theory, it has the freedom to consider any number of factors, such as the current network traffic, the load on the database, the current results sets it has available, etc. In practice LINQ to SQL does not consider all these factors, but it is free in theory to do pretty much what it wants. Furthermore, one could pass this expression tree to some custom code you write by hand which could analyze it and translate it into something very different from what is produced by LINQ to SQL.

Marlon Grech shows how to work with expression trees and create an expression parser.  A summary of the expression tree expressions class hierarchy is provided by Octavio Hernández.

Time to stop adding to c#? by Jim Leonardo Posted
  1. Back to top

    Time to stop adding to c#?

    by Jim Leonardo

    With all that they're trying to jam into c#, would it be better to just come up with a new language to encapsulate these features rather than coming up with more and more syntax? I wonder if c# can be reduced into a formal grammar anymore? That is another way of saying its harder to build tools for things like code analysis, code generation, etc.

Educational Content

New-age Transactional Systems - Not Your Grandpa's OLTP

John Hugg discusses high volume transaction processing applications with high and low frequency profiles, and how VoltDB can be used for that purpose.

Cool Code

Kevlin Henney examines code samples to see what can be learned from them starting from the premise that one won’t write great code unless he knows how to read it.

Collaboration: At the Extremities of Extreme

Jason Ayers share the observations he made watching a team of developers collaborating in real time on the same code base, pushing XP, pair programming and continuous integration to their extremes.

Yesod Web Framework

Michael Snoyman presents Yesod, a web framework written in Haskell and containing a web server, templating, ORM, libraries (templating, gravatar, etc.).

Transactions without Transactions

Richard Kreuter and Kyle Banker on how to avoid classical RDBMS transactional systems by using compensation mechanisms, transactional messaging or transactional procedures.

Attila Szegedi on JVM and GC Performance Tuning at Twitter

Attila Szegedi talks about performance tuning Java and Scala programs at Twitter: how to approach GC problems, the importance of asynchronous I/O, when to use MySQL/Cassandra/Redis, and much more.

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.