Delphi - Equivalent to C#'s ternary operator?

21,127

Solution 1

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;

Solution 2

The closest you can get to a ternary operator is:

if (condition) then <statement> else <statement>;

As far as I remember, there is no ternary operator in Delphi.

Solution 3

Try the Iff from Jedi:

function Iff(const Condition: Boolean; const TruePart: string; const FalsePart: string): string; overload;
function Iff(const Condition: Boolean; const TruePart: Char; const FalsePart: Char): Char; overload;
function Iff(const Condition: Boolean; const TruePart: Byte; const FalsePart: Byte): Byte; overload;
function Iff(const Condition: Boolean; const TruePart: Integer; const FalsePart: Integer): Integer; overload;
function Iff(const Condition: Boolean; const TruePart: Cardinal; const FalsePart: Cardinal): Cardinal; overload;
function Iff(const Condition: Boolean; const TruePart: Float; const FalsePart: Float): Float; overload;
function Iff(const Condition: Boolean; const TruePart: Boolean; const FalsePart: Boolean): Boolean; overload;
function Iff(const Condition: Boolean; const TruePart: Pointer; const FalsePart: Pointer): Pointer; overload;
function Iff(const Condition: Boolean; const TruePart: Int64; const FalsePart: Int64): Int64; overload;
function Iff(const Condition: Boolean; const TruePart: Variant; const FalsePart: Variant): Variant; overload;
Share:
21,127
Simon
Author by

Simon

Technical Coordinator at Fugro TSM, Perth Australia B. Eng Software Engineering Delphi / C# / SQL Server / MySQL Experienced in subsea hardware communications and system development, database admin and creation, experienced radiographer and digital video application development and solutions.

Updated on April 10, 2020

Comments

  • Simon
    Simon about 4 years

    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?