VB.NET - IIF(,,) - Both "sides" are evaluated. What situations should I watch out for?

Here is the most common gotcha.

Z = iif(y=0, 0, x/y)  'Throws a divide by zero exception when y is 0

Don't use it to avoid division by zero errors.

Another possible logic bug is when one side of the iif or the other calls a method that modifies the system state or has output parameters.

Z = iif(FunctionA(InputOutputParam), FunctionB(InputOutputParam))
'InputOutputParam is indeterminate or at least ambiguous here.

There really is no good reason to use IIF in my experience. Mostly it is just used to abbreviate code and given the problems it can cause, it just isn't worth it. Plus, I think it makes the code harder to read.

The other thing that bites is that it returns a boxed value (ie an Object data type) which you have to cast back to the desired type.


[IIF, not IFF]

The most common case we've seen is that one side or the other evaluates to Nothing.

Your code might be expecting to use IIF as guard to keep from getting a NullReferenceException, like this:

IIF(something Is Nothing, "nothing", something.Value)

But that won't work, because both sides are always evaluated. This happens a lot in code written by people who come from a C/C++/C#/Java background, since in those languages the ternary operator ?: does short-circuit evaluation.

And the fact that the VS 2005 IIF() documentation states that IIF is just like ?: doesn't help:

The IIf function provides a counterpart for the ternary Conditional Operator: ? : in Visual C++.

Nowhere on that reference page does it state that both sides are evaluated.


According to MSDN, the "If" operator introduced in VB2008 will short-circuit instead, which would be ideal for your expensive computation case:

http://msdn.microsoft.com/en-us/library/bb513985.aspx


Well, you should also make sure you don't have any functions in in iif that modifies any data based on the condition. We use If for a rather lot of that. It just pays to remember that about iif.