C# Expression Trees

Just a quick example that you can try yourself. It can be hard to write and debug Expression Trees but they are very powerful.

using System;
using System.Linq.Expressions;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Func<int, int> f = (x) => x + 1; // Same as: x++
var result = f(1);
Console.WriteLine("My result: " + result);

// ------

var result2 = f.Invoke(1);
Console.WriteLine("My result (via Invoke): " + result2);

// ------

ParameterExpression param0 = Expression.Parameter(typeof(int)); // first parameter
ParameterExpression param1 = Expression.Parameter(typeof(int)); // second parameter
ConstantExpression const0 = Expression.Constant(1);             // a constant

BinaryExpression expr = Expression.Add(Expression.Subtract(param1, const0), param0); // Same as: param1 - constant + param0
Expression<Func<int, int, int>> lambdaExpr = Expression.Lambda<Func<int, int, int>>(expr, param0, param1); // creates the lambda delegate

Func<int, int, int> compiledExpr = lambdaExpr.Compile(); // compiles the expression tree
var result3 = compiledExpr(1, 1); // executes the epxression tree with param0 and param1

Console.WriteLine("My result via Expression: " + result3);

// Don't close the console directly
Console.ReadLine();
}
}
}

See also the ExpandoObject in C#.

Enjoy ;)

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s