useful IIf for Visual Basic 2005
The 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…
June 16th, 2005 at 9:04 pm
Dont you have to do something like IIf(Integer)(SomeCondition(), 10, 20), to pick the correct type??
June 17th, 2005 at 3:26 pm
Actually, through a feature called “type inferencing”, you don’t need to specify the type parameters of a generic function. The Visual Basic compiler will determine/infer the correct set of type parameters based on the types of the arguments you call the function with. In the example above, it will infer the type Integer because 10 and 20 are Integer literals. Don’t worry, if it can’t figure it out, the compiler will give you an error. It won’t do anything surprising/unintuitive.
See also this excellent paper on VB generics written by my friend and former coworker Harish Kantamneni.