IIf is a function that exists in older versions of Visual Basic (before .Net) and in Visual Basic for Applications (VBA). The function has the following syntax:
IIf( <expression>, <truepart>, <falsepart> )
It will return either the true part or the false part, depending on the evaluation of the expression in the first argument.
The IIf function has been carried forward into the Visual Basic.Net language, through the Microsoft.VisualBasic.dll assembly. Recently, I discovered that this function has some potential downsides to its use. For example, if you try:
IIf ( 1 = 1, MsgBox("True"), MsgBox("False") )
then you'll see the message "True" followed immediately by the message "False". The reason for this is that because IIf is a function, all the arguments to the function are evaluated regardless of which one is eventually returned. Effectively, the compiler is doing the following:
expr1 = ( 1 = 1)
expr2 = MsgBox("True")
expr3 = MsgBox("False")
IIf( expr1, expr2, expr3 )
The only way to avoid such side effects is to rewrite the code as follows:
If( 1 = 1 ) Then
MsgBox("True")
Else
MsgBox("False")
End If
In VB 9.0 (the version of VB that ships with Visual Studio 2008), there is now a "ternary" version of If that behaves as you would expect, so:
If( 1 = 1, MessageBox.Show("True"), MessageBox.Show("False") )
will just display the message "True". In addition, if you only supply two arguments, then the If function can also act as a null-coalescing operator:
Dim name As String = Nothing
If ( name, "Default name" )
returns "Default name", which is especially useful if you're working with Nullable types and need to convert them into some 'default value' to display on a form or web page.