public Method1(Expression<Func<T, TProperty>> valueToCompare) {
//Examine expression
}
public Method1(TProperty valueToCompare) : this(x => valueToCompare) {}
and i run them like this
Method1(x => 1);
and
Method1(1);
If i examine the expression when the first overload is called then I get a constant expression. However when I examine the second one I get a member expression.
The question is how do I get access to the value ‘1’ no matter which overload i call.
Update1:
I used to do this until I realised the didn’t both return the same thing.
if (valueToCompare.Body.NodeType == ExpressionType.Constant)
{
var constant = valueToCompare.Body as ConstantExpression;
ValueToCompare = constant != null ? (TProperty)constant.Value : default(TProperty);
}
What will i get if I compile it?
Tried to do this but it didn’t work.
if (ValueToCompare .Body.NodeType == ExpressionType.MemberAccess) {
var member = ValueToCompare .Body as MemberExpression;
if (member.Expression.NodeType == ExpressionType.Constant)
{
ConstantExpression constant = member.Expression as ConstantExpression;
ValueToCompare = constant.Value;
}
}
Cheers.
Are you happy to just compile the expression and run it? That would seem the easiest solution to me…
Alternatively, you could make your overload taking a
TPropertyexplicitly construct a constant expression, rather than using a lambda expression. It really depends on what you’re trying to achieve.As an example of the latter approach, you’d write something like (untested):