I need to use ExpressionVisitor to analyse an Expression before executing it. For my needs, i need to evaluate the right part of a Divide expression but i don't know how to do it. Here's a sample code that i have:
internal class RulesChecker : ExpressionVisitor
{
private readonly object data;
public RulesChecker(object data)
{
this.data = data;
}
protected override Expression VisitBinary(BinaryExpression node)
{
if (node.NodeType == ExpressionType.Divide)
{
var rightExpression = node.Right;
// compile the right expression and get his value
}
return base.VisitBinary(node);
}
}
Suppose that i have this code to evaluate:
Expression<Func<DataInfo, decimal?>> expression = x => x.A / (x.B + x.C);
var rulesChecker = new RulesChecker(data);
rulesChecker.Visit(expression);
In the VisitBinary function, i will receive a node that will contain the left and right part of the divide operation. My question is, how can i evaluate the value that i will get in the right part of the operation?
I think the hardest part of this problem is dealing with the variables. So I would start by replacing the variables for constants. After that you just need to execute and update the Expression.