Implementing Immediate If (IIF) in Delphi

I have never regretted moving from C++ to Object Pascal, but I did

miss a useful feature of C - the Immediate If (iif).



It seems like a great deal of my code involves simple if statements

such as -





  if LambCount = 1 then

  begin

    AString := 'a';

    LambString := 'lamb';

  end else

  begin

    AString := '';

    LambString := 'lambs';

  end;



  FullString := 'Mary had ' + AString + ' little ' + LambString;



The introduction of method overloading in Delphi 4 enabled me to

create my own verison of iif in Object Pascal.



The following code is part of standard utility unit I include in all

my projects:



{begin listing}



unit StandardUtils;



interface



function IIF(Condition: Boolean;

             TrueString : String;

             FalseString: String = ''): String; overload;

function IIF(Condition: Boolean;


             TrueInt : Integer;

             FalseInt: Integer = 0): Integer; overload;



implementation



{********************************************************************}

function IIF(Condition: Boolean;

             TrueString : String;

             FalseString: String = ''): String; overload;

begin

  if Condition then

    result := TrueString

  else

    result := FalseString;

end;



{********************************************************************}

function IIF(Condition: Boolean;

    TrueInt : Integer;

            FalseInt: Integer = 0): Integer; overload;

begin

  if Condition then

    result := TrueInt

  else

    result := FalseInt;

end;



{********************************************************************}

end.



{end listing}

 

Share this article!

Follow us!

Find more helpful articles: