Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Equivalent to C#'s ternary operator? [duplicate]

Possible Duplicate:
Is there, or is there ever going to be, a conditional operator in Delphi?

I understand Delphi doesnt have the ternary operator as in C#. i.e. ?:

So how best to represent this function call? Whats the cleanest method out there?

Would be very nice if there is any code out there that can be used INSTEAD of writing a separate function? If not, whats the most efficient and/or cleanest code representation of it?

like image 958
Simon Avatar asked Mar 09 '11 06:03

Simon


1 Answers

Of course you can use

IfThen(SomeBooleanExpression, IfTrueReturnValue, IfFalseReturnValue) 

where the return values are numeric (uses Math) or string (uses StrUtils). But notice that this will evaluate both arguments in all cases -- there is no lazy evaluation, so it is not as efficient as the ?: operator in C#, where only the right operand is evaluated.

So you cannot do

y := IfThen(x <> 0, 1/x, 0) 

The best thing is to stick with an ordinary

if x <> 0 then y := 1/x else y := 0; 
like image 146
Andreas Rejbrand Avatar answered Sep 24 '22 08:09

Andreas Rejbrand