IIf Function |
Microsoft.VisualBasic.Interaction
IIf( expression , truepart , falsepart )
Expression to be evaluated
Expression or value to return if expression is True
Expression or value to return if expression is False
The value or result of the expression indicated by truepart or falsepart
Returns one of two results, depending on whether expression evaluates to True or False
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.
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 improved significantly, although it remains significantly slower than an If statement. The average number of seconds required to call the IIf function a million times and to execute an If...ElseIf...Else...End If statement a million times under the two VB versions showed the following differences:
IIf function | If statement | |
---|---|---|
VB 6 | 11.09 | 0.52 |
VB.NET | 6.12 | 0.02 |
In other words, the performance of IIf from VB 6 to VB.NET has improved by 100%. At the same time, the function is over 300 times slower than an If statement under VB.NET!
If...Then...Else Statement