As part of a WPF application I'm building an expression tree and generating a Predicate to use as a filter. The code looks something like this:
public Expression BuildExpression(Expression parameter, string value)
{
MethodInfo toStringMethod = new Func<Object, string>((a) => a.ToString()).Method;
Expression lhs = Expression.Call(parameter, toStringMethod );
ConstantExpression rhs = Expression.Constant(value);
BinaryExpression result = Expression.Equal(lhs, rhs);
return result;
}
This is because the parameter is an Expression of unknown type - it might be an int, string, Guid or anything else. The problem is that it's difficult to understand what's going on here without copious comments. I'd really like to use a lambda here:
return parameter => parameter.ToString() == value;
The problem is that this doesn't work as intended - the resulting delegate would call ToString() on the Expression instead of the value of the expression. If it helps, parameter is a MemberExpression.