lundi 12 avril 2021

How to reference a method parameter from lambda in C#

Given this lambda

public static Expression<Func<int, int>> Add(int add)
{
    return x => x + add;
}

it creates the following debug output:

.Lambda #Lambda1<System.Func`2[System.Int32,System.Int32]>(System.Int32 $x) {
    $x + .Constant<ConsoleAppExpressionTest.Program+<>c__DisplayClass1_0>(ConsoleAppExpressionTest.Program+<>c__DisplayClass1_0).add
}

The debug view shows that the field add is addressed within a constant.

How to create the same lambda dynamically?

What i've tried:

public static Expression<Func<int, int>> Add(int add)
{
    var x = Expression.Parameter(typeof(int), "x");
    var expr = Expression.Add(x, Expression.Field(Expression.Constant(null), "add"));

    return Expression.Lambda<Func<int, int>>(expr, x);
}

leads into a System.ArgumentException: 'Instance field 'add' is not defined for type 'System.Object''.

While using the parameter directly as constant would just create a copy of the value: Expression.Constant(add)





Aucun commentaire:

Enregistrer un commentaire