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:
- When using Option Strict On, you need to cast the return value to the correct type. Which is
normally rather “awkward”.
- Because the parameters are Object; value types used as parameters will be boxed and unboxed on return.
- 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
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)
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