IIF Issues

This applies to MS .NET Framework; IIF.

1.) It doesn't support function call for its return value part (truepart and falsepart), however it supports function call for its expression part.

2.) It cannot be used as short-circuit. It will evaluate all three parameters. If you want to use it as short circuit, you have to use the conventional if-else structure.

Examples:

1.) The following code will trigger exception because it invokes CInt() method at the falsepart.

Dim tempNum As Integer
        Dim tempID As String

        Try

            tempID = ""
            tempNum = IIf(tempID = "", 0, CInt(tempID))
            MsgBox(tempNum)

        Catch ex As Exception
            MsgBox(ex.ToString & vbCrLf & ex.Message)
        End Try

--> The solution is not to use IIF for this scenario, use the conventional if-else construct.

2.) The following code will trigger exception because tempObj is null and when it tries to evaluate tempObj.Tag; exception. This is because IIF cannot be used as short-circuit, it has to evaluate all three parameters (express, truepart,falsepart) whenever it is invoked.

Dim tempObj As ToolTip
        Dim tempStr As String

        Try

            tempObj = Nothing

            tempStr = IIf(tempObj Is Nothing, "Nothing", tempObj.Tag)

            MsgBox(tempStr)

        Catch ex As Exception
            MsgBox(ex.ToString & vbCrLf & ex.Message)
        End Try


--> The solution is not to use IIF for this scenario, use the conventional if-else construct (which is considered to be short-circuit construct).

Comments