when I run this code
Expression left = Expression.Constant(10, typeof(int));
Expression right = Expression.Constant(10,typeof(int));
var method10 = typeof(Expr
You don't need reflection, unless I'm missing something:
Expression left = Expression.Constant(10, typeof(int));
Expression right = Expression.Constant(10,typeof(int));
Expression exp = Expression.Equal(left, right);
var lambda = Expression.Lambda<Func<bool>>(exp);
Clearly you could manually call the int.Equals(int)
method...
var method10 = left.Type.GetMethod("Equals", new[] { right.Type });
Expression exp = Expression.Call(left, method10, right);
var lambda = Expression.Lambda<Func<bool>>(exp);
but note that there is a subtle difference: Expression.Equal
will use the ==
operator, while the other code will use the Equals
method.
If you really want to build an expression from a string:
string methodName = "Equal";
MethodInfo method10 = typeof(Expression).GetMethod(methodName, new[] { typeof(Expression), typeof(Expression) });
Expression exp = (Expression)method10.Invoke(null, new object[] { left, right });
var lambda = Expression.Lambda<Func<bool>>(exp);
or
ExpressionType type = (ExpressionType)Enum.Parse(typeof(ExpressionType), methodName);
var exp = Expression.MakeBinary(type, left, right);
using the Enum.Parse
I solved it . thanks guys
Expression left = Expression.Constant(10, typeof(int));
Expression right = Expression.Constant(10, typeof(int));
ExpressionType expressionType;
var tryParseRes = ExpressionType.TryParse("NotEqual", out expressionType);
var exp = Expression.MakeBinary(expressionType, left, right);
var lambda = Expression.Lambda<Func<bool>>(exp);
var compiled = lambda.Compile().DynamicInvoke();
if ((bool)compiled == false)
areEventCondiotionsPassed = false;
Try
var exp = Expression.MakeBinary(ExpressionType.Equal, left, right);
instead of
var method10 = typeof(Expression).GetMethod("Equal", new[] { typeof(Expression), typeof(Expression) });
Expression exp = Expression.Call(method10,left,right);