Search code examples
c#expression-trees

How can I create an expression that either throws an exception or returns a value based on a condition?


I'm struggling to build an expression that if the condition is true throws an exception and if it's false that it should return a value but I'm always getting the ArgumentException:

var expr =
    Expression.Condition(
        Expression.Equal(Expression.Constant(0), Expression.Constant(0)),
        Expression.Throw(Expression.Constant(new DivideByZeroException())),
        Expression.Constant(1));
var lambda = Expression.Lambda<Func<int>>(expr);
var result = lambda.Compile()();

If I put Expression.Empty() as the third argument of the Condition it then runs but I don't get the desired result if the condition is false.


Solution

  • This does it.

    var expr =
        Expression.Block(
            Expression.IfThen(
                Expression.Equal(Expression.Constant(1), Expression.Constant(1)),
                Expression.Throw(
                    Expression.New(typeof(DivideByZeroException))
                )
            ),
            Expression.Constant(1)
        );
    var lambda = Expression.Lambda<Func<int>>(expr);
    var result = lambda.Compile()();
    

    Conditional is more similar to the ternary operator. So what you were writing was more equivalent to in C#:

    return (0 == 0) ? throw new DivideByZeroException() : 1;
    

    I changed your constant exception to a dynamically created one, I'm assuming that is preferred.