Search code examples
c#genericslambdaexpressionexpression-trees

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.


Solution

  • 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)
    }