Eli Weinstock-Herman

IF and IIF in VB.Net

Original post posted on Wednesday, June 23, 2010 at LessThanDot.com

In continuing Chrissie's recent example of helping to point out minor (yet critical) gotchas, I now present the guarantor of a few Null Reference exceptions, If() and IIf().

Both are designed as a way to provide VB.Net with an inline If, similar to the ternary operator found in C# and many other languages <condition>?<true-action>:<false-action>. If() and IIF() have the same signature: If(<conditional>,<true-object>,<false-object>) and IIF(<conditional>,<true-object>,<false-object>)

The critical difference between IIF (available from VS 2002 forward) and IF (available in VS 2005 forward) is that IIF is a function and evaluates all of its arguments prior to returning a value, while IF is an operator that executes like a short-circuiting conditional, only evaluating the true or false argument depending on the value of the conditional.

Why is this important?

Code: vb.net
Dim myObject as SomeObject
Dim strTestOne = If(myObject Is Nothing,"Doesn't Exist",myObject.SomeProperty())
' strTestOne now has the value "Doesn't Exist"
Dim strTestTwo = IIf(myObject Is Nothing,"Doesn't Exist",myObject.SomeProperty())
' and this one throws a null reference because it evaluates myObject.SomeProperty prior to the conditional

So make sure you select the right function for your needs. In this case, selecting the wrong function can actually have the exact consequence you were trying to avoid (Null Ref).

Note: Not only a whole post without pictures, but also one that is less than 10 pages. And the sky didn't start falling.

Comments are available on the original post at lessthandot.com