Expression Trees C# 3.0 Part II - Building Expression Trees - C# 3.0 Examples and Tutorials

Expression Trees C# 3.0 Part II - Building Expression Trees - C# 3.0 Examples and Tutorials

by David Hayden ( .NET C# Developer ), C# 3.0 Examples and Tutorials

 

I talked about Expression Trees earlier:

with regards to a simple delegate stored as data in an Expression Tree:

 

Expression<Func<int,int>> expression = x => x + 1;

 

The expression tree above essentially describes the delegate. In fact, we can build the expression tree as well as compile and invoke the delegate it describes using the following code:

 

// Create the parameter "x" in x + 1
ParameterExpression p0 =
Expression.Parameter(typeof(int), "x"); // Create the constant 1 in x + 1 ConstantExpression c0 = Expression.Constant(1); // Build the addition expression x + 1 using the above // Note it will really look like Add(x,1) BinaryExpression expression = Expression.Add(p0, c0); // Create the Lamda Expression x => Add(x,1) var lambdaExpression = Expression.Lambda<Func<int,int>>
(expression, new ParameterExpression[] { p0 }); // Let's compile it so we can use it var theDelegate = lambdaExpression.Compile(); // Execute... 6 + 1 = 7 var seven = theDelegate.Invoke(6);

 

I think the comments above explain the process pretty well. Pretty cool stuff in C# 3.0.

by David Hayden ( .NET C# Developer )

Filed: C# 3.0 Examples and Tutorials

posted on Thursday, December 21, 2006 9:29 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices