Search code examples
c#.netreflectionexpression-trees

Calling parameterised constructor using compiled expression


I'm trying to create a compiled expression delegate to call a constructor taking a single parameter, I'm receiving the following exception:

Additional information: variable 'value' of type 'MyType' referenced from scope '', but it is not defined

The code is as follows:

var constructorInfo = instanceType.GetConstructors().Skip(1).First();

ParameterExpression param = Expression.Parameter(genericArgument, "value");
Delegate constructorDelegate = Expression.Lambda(Expression.New(constructorInfo, new Expression[] { param })).Compile();

I believe I'm receving the exception because the parameter 'value' is not scoped inside an Expression.Block.

How do I scope the parameter & constructor expressions inside an Expression.Block?


Solution

  • In order to declare the parameter value, you need to also specify it when creating the Lambda expression (see this overload of the Expression.Lambda method). Up to now, you only create a parameterized lambda expression, but do not declare the parameters that are used in the expression. Changing your code should solve the issue:

    var lambdaExpr = Expression.Lambda(Expression.New(constructorInfo, 
                                                      new Expression[] { param }), 
                                       param);
    Delegate constructorDelegate = lambdaExpr.Compile();