useful IIf for Visual Basic 2005
Wednesday, June 8th, 2005The IIf statement in Visual Basic is a pain when Option Strict is on. The reason is that the return value is Object and thus requires a cast back to the target type:
Dim a As Integer = IIf(SomeCondition(), 10, 20)
Error: Option Strict On disallows implicit conversions from 'System.Object' to 'Boolean'.
To fix the compile error, you need to add a cast:
Dim a As Integer = CInt(IIf(SomeCondition(), 10, 20))
Even worse, use an enum:
Dim b As Color = CType(IIf(SomeCondition(), Color.Red, Color.Blue), Color)
But by using generic methods and type inferencing, you can create a version of IIf that eliminates the need for the cast:
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 Function
Then the above examples could be written as:
Dim a As Integer = IIf(SomeCondition(), 10, 20)
Dim b As Color = IIf(SomeCondition(), Color.Red, Color.Blue)
Much nicer. And also much faster because we avoid boxing the parameters and unboxing the result. Now if only IIf could be massaged into a real ternary operator…