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.

Leave a Comment