Search code examples
c#lambdaexpressionexpression-trees

How to add parameter that will never be used to expression tree in C#?


I have a method in my code MyMethod: public void MyMethod(String input). It is a method for MyNamespace.MyClass, and the instance of MyClass that I am using is MyObject. I am creating an event handler that calls MyObject.MyMethod with the input parameter always set to "test". However, I am creating it using an expression tree. Here is my current code, which manages to set input, but not the required Object and EventArgs parameters of an event handler:

Expression.Lambda(Expression.Call(Expression.Constant(MyObject), typeof(MyNamespace.MyClass).GetMethod("MyMethod"), Expression.Constant("test"), Expression.Parameter(typeof(Object), "sender"), Expression.Parameter(typeof(EventArgs), "e"))).Compile();

I get error: Incorrect number of arguments supplied for call to method 'Void MyMethod(System.String)'.

When I try to define the last two Expression.Parameters directly under Expression.Lambda, I get a Parameter count mismatch error.

The last working code I have simply takes out the last two Expression.Parameters completely.

How can I define these parameters, even though I will not use them, to make the method into an event handler?


Solution

  • You have a misplaced closing parenthesis. sender and e are parameters of the Lambda and not of MyMethod, they should added as parameters in Expression.Lambda :

    Expression.Lambda(
        Expression.Call(Expression.Constant(MyObject), typeof(MyClass).GetMethod("MyMethod"), Expression.Constant("test")), 
        Expression.Parameter(typeof(Object), "sender"), 
        Expression.Parameter(typeof(EventArgs), "e")
    ).Compile();
    

    Notice the Expression.Call closing parenthesis is after Expression.Constant("test")