IIf(Of T) — A type safe IIf function that works with Option Strict On

Problem

Microsoft.VisualBasic.Interaction.IIf is a function that accepts two Object values & returns an Object value. VB’s IIf has the following problems:

  1. When using Option Strict On, you need to cast the return value to the correct type. Which is normally rather “awkward”.
  2. Because the parameters are Object; value types used as parameters will be boxed and unboxed on return.
  3. Its a function, so both the truePart & falsePart parameters will be evaluated.

Because of the “awkwardness” of the casting I normally avoid IIf in VB.NET 2002 & 2003.

Solution

With VB.NET 2005 one can define a Generic version of IIf that does not have the first two issues above.

NOTE: The Generic IIf is still a function, so both the truePart & falsePart parameters will still be evaluated.

Discussion

The generic IIf(Of T) function avoids the need (the "awkwardness") of the DirectCast. I would consider using the Generic IIf as it may simplify some expressions…

You can use IIf(Of T) as you would VB.IIf, the compiler is able to infer the parameter type for T. When inferring the parameter types IIf(Of T) works best when both truePart & falsePart parameters are the same type.

However! the “problem” with both VB.IIf & my IIf(Of T) is that both operands are evaluated which may have undesired side effects.

Example

Example 1

Visual Basic 2005
 
Option Strict On

    Dim i As Integer
    Dim s As String
    Dim d As Decimal
    Dim f As Single
        
    i = IIf(1 = 2, 1, 2)
    s = IIf(s Is Nothing, "Empty", s)
    d = IIf(False, 5D, 6D)
    f = IIf(True, 1.0F, 2.0F)

Source

IIf(Of T)

Visual Basic 2005
 
Public Function IIf(Of T)(ByVal expression As Boolean, _
        ByVal truePart As T, ByVal falsePart As T) As T
    If expression Then
        Return truePart
    Else
        Return falsePart
    End If
End Function