The IIF function in Microsoft VB is a statement that allows you to evaluate an expression and return one of two objects depending on the result of the evaluation. Neat.
The problem that I had with IIF is that it always evaluates the true and false parts of the statement no matter the result of the expression. Let’s assume this bit of code:
Dim _result As String
_result = IIf(_object Is Nothing, “”, _object.PropertyValue)
If _object is not nothing/null then this statement works just fine. However; if _object is nothing/null, the _object.PropertyValue is evaluated and a null reference exception is thrown. Pooh….
This can get even worse if you are calling a routine in the true/false portions of the statement.
IIf(_object Is Nothing, DoSomething(), DoSomethingElse())
In this case, BOTH DoSomething and DoSomethingElse routines will be executed. Double Pooh!
IF to the rescue. IF now has an overload that allows the same basic functionality of IIF but without the above problems. Additionally, it is close to matching the functionality of the C# conditional ternary operator (?).
Dim _result As String
_result = If(_object Is Nothing, “”, _object.PropertyValue)
OR
IIf(_object Is Nothing, DoSomething(), DoSomethingElse())
Maybe worth mentioning here, the relatively new Nullable data types can be quite useful. The following is an example of using the Nullable HasValue method instead of an “Is Nothing”/”= null” evaluation.
If(_object.PropertyName.HasValue, _object.PropertyName, “”)
The point to all of the above is to be careful with IIF when null/nothing objects/properties can exist. Or, be safe and use IF instead.
Leave a Reply