Saturday, April 26, 2008

Immediate If

Visual Basic programmers have a function at their disposal called IIf(), which is an abbreviation for Immediate If.


result = IIf(2 + 2 = 5, "Correct", "Wrong")

The iif() function is sometimes more convenient than a full-blown if...then...else... control structure. Oddly enough, the function does not exist in VBScript.

Our PHP programmer friends have a superior equivalent, the ternary operator.


$result = (2 + 2 = 5) ? 'Correct' : 'Wrong';

Unfortunately we can't recreate the ternary operator in ASP, but we can recreate the iif() function.


  1. function IIf(expression, truecondition, falsecondition)
  2.     if isNull(expression) then
  3.         IIf = falseCondition
  4.     elseif cbool(expression) then
  5.         IIf = truecondition
  6.     else
  7.         IIf = falsecondition
  8.     end if
  9. end function


Stephen R said...

Even better if you add an isNull check to the beginning. Your function crashes if expression evaluates to NULL.

if isNull()... elseif cbool()... else....

Scott said...

Thanks Stephen! I've updated the code above.