Search code examples
c#lambdaexpressionexpression-trees

Getting error "Static method requires null instance, non-static method requires non-null instance." while trying to execute expression tree in C#


In C#, I have a class MyNamespace.MyClass, and in that class there is defined a method MyMethod. I am trying to call this method upon MyObject, an instance of the MyClass class, but I am getting the error in the title. Here is my code:

Expression.Lambda(Expression.Call(typeof(MyNamespace.MyClass).GetMethod("MyMethod"), Expression.Constant("MyParam"))).Compile().Method.Invoke(MyObject, null);

MyMethod is not a static method. What am I doing wrong?


Solution

  • The overload of Expression.Call that takes the MethodInfo first is for static methods. You need this one: Expression.Call, eg to compile a delegate that calls myObject.MyMethod("MyParam") would be:

        var f = (Action)Expression.Lambda(Expression.Call(Expression.Constant(myObject), typeof(MyClass).GetMethod("MyMethod"),  Expression.Constant("MyParam"))).Compile();
    
        f();