Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Generic Method using Lambda Expressions (and a Type only known at runtime)

You can use Lambda Expression Objects to represent a lambda as an expression.

How do you create a Lambda Expression Object representing a generic method call, if you only know the type -that you use for the generic method signature- at runtime?

For example:

I want to create a Lambda Expression Objects to call: public static TSource Last<TSource>( this IEnumerable<TSource> source )

But I only know what TSource is at runtime.

like image 311
SDReyes Avatar asked May 17 '10 15:05

SDReyes


2 Answers

static Expression<Func<IEnumerable<T>, T>> CreateLambda<T>()
{
    var source = Expression.Parameter(
        typeof(IEnumerable<T>), "source");

    var call = Expression.Call(
        typeof(Enumerable), "Last", new Type[] { typeof(T) }, source);

    return Expression.Lambda<Func<IEnumerable<T>, T>>(call, source)
}

or

static LambdaExpression CreateLambda(Type type)
{
    var source = Expression.Parameter(
        typeof(IEnumerable<>).MakeGenericType(type), "source");

    var call = Expression.Call(
        typeof(Enumerable), "Last", new Type[] { type }, source);

    return Expression.Lambda(call, source)
}
like image 112
dtb Avatar answered Nov 19 '22 05:11

dtb


I don't fully understand the question, but the code that dtb wrote could be written simply as:

class MyUtils {
  public static Expression<Func<IEnumerable<T>, T>> CreateLambda<T>() { 
    return source => source.Last();
  }
}

The code in the sample by dtb is pretty much the same thing as what the C# compiler automatically generates for you from this lambda expression (compiled as expression tree, because the return type is Expression).

If you know the type at runtime, then you can either use the solution by dtb or you can invoke the CreateLambda method (above) using Reflection, which may be slower, but allows you to write the code in the lambda in the natural C#:

var createMeth = typeof(MyUtils).GetMethod("CreateLambda");
LambdaExpression l = createMeth.MakeGenericMethod(yourType).Invoke();

The nice thing about this approach is that the code in CreateLambda can be much more complicated, which would be really hard to do using expression trees explicitly.

like image 43
Tomas Petricek Avatar answered Nov 19 '22 05:11

Tomas Petricek