"Incorrect number of parameters supplied for lambda declaration"

c# expression expression-trees func

Question

When I have this,

public static object Create()
{
    return new object();
}

this works:

var m = typeof(Class).GetMethod("Create");
var e = Expression.Call(m);
Func<object> f = Expression.Lambda<Func<object>>(e).Compile();

But when I have this,

public static object Create(Type t)
{
    return new object();
}

this fails:

var m = typeof(Class).GetMethod("Create");
var e = Expression.Call(m, Expression.Parameter(typeof(Type)));
var t = Expression.Parameter(typeof(Foo));
Func<object> f = Expression.Lambda<Func<object>>(e, t).Compile();

I get An unhandled exception of type 'System.ArgumentException' occurred in System.Core.dll. Additional information: Incorrect number of parameters supplied for lambda declaration. The parameter t is just expression for a dummy type Foo. I think that's irrelevant. Where have I gone wrong here?

Accepted Answer

The problem is that you've said you want to use a parameter - but then you're not actually providing anywhere to specify it. You were creating two ParameterExpressions of different types, and then trying to convert the result into a Func<object> - which doesn't have any parameters at all. You want something like:

var m = typeof(Class).GetMethod("Create");
var p = Expression.Parameter(typeof(Type), "p");
var e = Expression.Call(m, p);
Func<Type, object> f = Expression.Lambda<Func<Type, object>>(e, p).Compile();

Note that the same ParameterExpression is used in the argument list for both theExpression.Call method and the Expression.Lambda methods.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why