Bryan
Bryan

Reputation: 5471

Rewriting a ? operator with an if-else in c#

Can I write this

 return (a, b) => (b == 0) ? 0: a / b;

With an if-else to the right of (a, b) =>

Upvotes: 0

Views: 110

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

If you are returning a Func<double, double, double> it could be re-written as

return (a, b) =>
    {
     if(b == 0)
        return 0;
     else
        return a / b; 
    };

If you are returning a Expression<Func<double, double, double>> it is not very easy to do, you will need to create a custom Expression by hand to represent the statement as there is no way to represent it in C#.

Have not tested it, but I think the Expression version would be

public Expression<Func<double, double, double>> IThinkThisWorks()
{
    var paramA = Expression.Parameter(typeof(double), "a");
    var paramB = Expression.Parameter(typeof(double), "b");
    var const0 = Expression.Constant(0.0);
    var test = Expression.Equal(paramA, paramB);
    var division = Expression.Divide(paramA, paramB);
    var ifCheck = Expression.IfThenElse(test, const0, division);
    return Expression.Lambda<Func<double, double, double>>(ifCheck, paramA, paramB);
}

Upvotes: 5

Related Questions