.Net, Azure and occasionally gamedev

Reflection (5/5) Dynamic code generation (System.Linq.Expressions)

2013/01/24

This is the fifth and last post in a series. All posts are short excerpts from my Reflection paper.

System.Linq.Expressions is part of the .Net Framework since v3.5. It has been greatly enhanced in v4.0.

It greatly simplyfies the generation of dynamic code in comparison to crafting manual IL code via Reflection.Emit.

While it is more limited (e.g. there is no dynamic type generation - only static methods can be compiled) it is a lot easier to use and can produce results quicker.

Lets take a look at a simple example:

public Func<int, int> CompileAddFunction(int offset)
{
    var numberToAdd = Expression.Parameter(typeof(int), "number");
    var addAmount = Expression.Constant(offset, typeof(int));
    var binaryExpression = Expression.Add(numberToAdd, addAmount);
    var lambda = Expression.Lambda<Func<int, int>>(binaryExpression, new ParameterExpression[] { numberToAdd });
    return lambda.Compile();
}

static void Main(string[] args)
{
    var newFunc = CompileAddFunction(3);
    var result = newFunc.Invoke(7); // Adds 7 + 3
}

This roughly translates to:

public static int Add(int number)
{
    const int offset = 3;
    return number + offset;
}

The advantage being that the constant number is now defined in the code at runtime.

As can be seen, it is a lot simpler to generate dynamic code using the System.Linq.Expressions namespace than it is when using Reflection.Emit. The downside is, that no new types can be introduced via this method. If new types are required, Reflection.Emit has to be used, however for smaller dynamic codegenerations, System.Linq.Expression is actually easier and suited better.

tagged as C# and Reflection