1
Vote

Converting Expressions with static method calls back into System.Linq Expressions

description

When converting methods back into System.Linq expressions via the ToExpression() method call, if the original expression had a static method call a null reference exception would occur in the ToExpression() method of the EditableMethodCallExpression class. The issue comes from the following line
"return Expression.Call(Object.ToExpression(), Method, Arguments.GetExpressions().ToArray<Expression>());" the property Object is null for static (Shared in VB) method calls. According to the MSDN Documentation for the Expression.Call method, the first parameter needs to be null for static method calls. Therefore, changing the method body tot he following resolves the issue:
 
    // Methods
    public override Expression ToExpression()
    {
        if (Object == null)
        {
            return Expression.Call(null, Method, Arguments.GetExpressions().ToArray<Expression>());
        }
        else
        {
            return Expression.Call(Object.ToExpression(), Method, Arguments.GetExpressions().ToArray<Expression>());
        }
    }

comments