VB.Net IIf Catch

Tuesday, February 12, 2008 by Greg Berlin

Well, literally seconds after posting the previous post, I stumbled across this old doozie and thought i'd blog it right away for future reference.

I've learned that with IIf Statements, such as the following:

myDropOffAddress = IIf(myDropOffBooking.Type = EBookingType.StorePickUp Or myDropOffBooking.Type = EBookingType.StoreDropoff, myDropOffBooking.Store.Address, myDropOffBooking.StopPoint.Address)

VB.Net evaluates the entire statement before assigning a value to myDropOffAddress.  What this means is that if the condition passes and the first value (myDropOffBooking.Store.Address) is to be used, but the second value (myDropOffBooking.StopPoint.Address) does not exist, Visual Studio will throw a Null Reference exception & won't compile.  This is really quite annoying as often the creation of those objects only happens based on the above criteria, so the actual execution will never fail, but VB prevents it from compiling in the first place. 

The solution?  Revert to the good old verbose If ... Then ... Else ... End If statement.  :|

UPDATE:  For a more elegant explanation of this condition, check out SecretGeek's "VB.Net Tip: IIF is a function, not a language feature"  blog post.  The fact that it's really just a funciton and not a language feature really puts it all in perspective really.

0 comment(s) for “VB.Net IIf Catch”