Expressions static method requires null instance non-static method requires non-null instance

c# expression-trees

Question

I'm new to using Expressions and am getting the following error:

System.ArgumentException : Static method requires null instance, non-static method requires non-null instance.
Parameter name: method

The code is as follows:

        int inP = 100;
        object inParam = inP;
        Type inParamType = inParam.GetType();

        ParameterExpression pe = Expression.Parameter(typeof(S), "pe");

        Expression left = Expression.Property(pe, typeof(S).GetProperty(propName));
        Expression right = Expression.Constant(inParam, inParamType);

        MethodInfo mi = inParamType.GetMethod(operand, BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(object) }, null);
        Expression e1 = Expression.Call(mi, left, right);

Popular Answer

You're using BindingFlags.Instance, so you'll only get back instance methods. Instance methods must be called as C# a.f(b), not f(a, b), and that translates to expression tree Expression.Call(left, mi, right), not Expression.Call(mi, left, right). That's what the exception is telling you:

Static method requires null instance, non-static method requires non-null instance.

In this case you have a non-static method, therefore you must pass in an instance on which to call the method.



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