Name
IIf Function
Class
Microsoft.VisualBasic.Interaction
Syntax
IIf(expression, truepart, falsepart)-
expression Use: Required
Data Type: Boolean
Expression to be evaluated
-
truepart Use: Required
Data Type: Any value or expression
Expression or value to return if
expressionisTrue-
falsepart Use: Required
Data Type: Any value or expression
Expression or value to return if
expressionisFalse
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
IIfwill evaluate only one oftruepartorfalsepart, depending on the value ofexpression.The
IIffunction is the equivalent of:If
testexpressionThenReturn truepartElseReturn falsepartEnd If
truepartandfalsepartcan be a variable, constant, literal, expression, or the return value of a function call.
Programming Tips and Gotchas
The
IIffunction is ideal for very simple tests resulting in single expressions. If you really feel the need,IIffunction calls can be nested; however, your code can very quickly become difficult to read. The following code fragment illustrates the use of a nestedIIffunction: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
IIffunction in favor of theIfstatement for all but the most simple uses because of its poor performance. In VB.NET, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access