O'Reilly logo

VB.NET Language in a Nutshell, Second Edition by Steven Roman PhD, Paul Lomax, Ron Petrusha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

IIf Function

Class

Microsoft.VisualBasic.Interaction

Syntax

IIf(expression, truepart, falsepart)
expression (required; Boolean)

Expression to be evaluated

truepart (required; any value or expression)

Expression or value to return if expression is True

falsepart (required; any value or expression)

Expression or value to return if expression is False

Return Value

The value or result of the expression indicated by truepart or falsepart

Description

Returns one of two results, depending on whether expression evaluates to True or False

Rules at a Glance

  • IIf will evaluate only one of truepart or falsepart, depending on the value of expression.

  • The IIf function is the equivalent of:

    If testexpression Then
        Return truepart
    Else
        Return falsepart
    End If
  • truepart and falsepart can be a variable, constant, literal, expression, or the return value of a function call.

Programming Tips and Gotchas

  • The IIf function is ideal for very simple tests resulting in single expressions. If you really feel the need, IIf function calls can be nested; however, your code can very quickly become difficult to read. The following code fragment illustrates the use of a nested IIf function:

    Dim x As Integer
    x = CInt(Text1.Text)
    MsgBox(IIf(x < 10, "Less than ten", IIf(x < 20, _
               "Less than 20", "Greater than 20")))
  • In previous versions of VB, developers tended to avoid the IIf function in favor of the If statement for all but the most simple uses because of its poor performance. In VB.NET, the performance of IIf has been ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required