I'm stuck on a lambda with a single int
parameter and a bool
return value:
Expression<Func<int, bool>> myFunc = x => x == 5;
First, I tried this that returns a new Func
that I can't make sense of; I was expecting a true
boolean value:
var boolResult = Expression.Lambda(myFunc).Compile().DynamicInvoke(5);
Then I tried to explictly set the function parameters and return type instead:
var param = Expression.Parameter(typeof(int), "x");
var fn = Expression.Lambda<Func<int, bool>> (myFunc, param).Compile();
, but this throws an error:
System.ArgumentException : Expression of type 'System.Func`2[System.Int32,System.Boolean]' cannot be used for return type 'System.Boolean'
Which is weird, but I tried to convert the expression:
var fn = Expression.Lambda<Func<int, bool>> (
Expression.Convert(myFunc,
typeof(Func<int, bool>))
, param).Compile();
var boolResult = fn.Invoke(5);
, this however did not help and gives the same error:
System.ArgumentException : Expression of type 'System.Func`2[System.Int32,System.Boolean]' cannot be used for return type 'System.Boolean'
Any idea of what I'm doing wrong here?