Basically I am compiling expression at run-time and then I am invoking them with the DynamicInvoke
methods there are all supposed to return Boolean value, but the problem is that when there is string comparison, it fails. Suppose an expression like that {x.SomeProp == "value"}
value of SomeProp is "value"
but when I Execute the DynamicInvoke
on that expression pass the appropriate object to it and cast the return value to bool
I get false
as an answer.
This is the code I use to build expression
public static Expression BuildExpression(string propName, Operator op, object value, ParameterExpression paramExp)
{
var expressionType = new ExpressionType();
var leftOperand = CreateExpression(paramExp, propName);
var rightOperand = leftOperand.Type.BaseType == typeof(Enum) ?
Expression.Constant(Enum.Parse(leftOperand.Type, value.ToString(), true)) : Expression.Constant(Convert.ChangeType(value, leftOperand.Type));
var fieldInfo = expressionType.GetType().GetFields(Enum.GetName(typeof(Operator), op));
var expressionTypeValue = (ExpressionType)fieldInfo.GetValue(op);
var binaryExpression = Expression.MakeBinary(expressionType, leftOperand, rightOperand);
returnExpression;
}
private static Expression CreateExpression(ParameterExpression type, string propName)
{
Expression body = type;
body = Expression.PropertyOrField(body, propName);
return body;
}
paramExp
basically is this
var param = Expression.Parameter(someObjectType, "x");
now this code is does great job building expressions, then I do
Expression.Lambda(exp, param).Compile();
on it, and then
copiledExp.DynamicInvoke(someObj);
it works okay when comparing int
, double
, float
, decimal
and even enum
values but recently I have come up to a problem comparing strings. It return false on any expression
this is the view of the expression that is getting built. I mean, this is return by the ToString()
method
"(x.SomeStringProp == \"stringValue\")"