Question

As part of a larger set of expressions, we have our divide case. It's simple enough

protected override Expression BuildDivideExpression(Expression left, Expression right)
{           
    return Expression.Divide(left, right);
}

I'd like to change it so that it returns 0 if left is 0, and as is if left != 0.. Something like this:

protected override Expression BuildDivideExpression(Expression left, Expression right)
{
    return Expression.Condition(left != 0, Expression.Constant(0), Expression.Divide(left, right))
}

But I can't figure out the conditional bit currently shown as "left != 0"

?

Was it helpful?

Solution

I think you mean if right is equal to zero you want the result to be zero. So you want to use Expression.Equal like so

protected override Expression BuildDivideExpression(Expression left, Expression right)
{
    return Expression.Condition(Expression.Equal(right, Expression.Constant(0)),
                                Expression.Constant(0), 
                                Expression.Divide(left, right))
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top