Thursday, September 18, 2008

Newsflash: IIf is NOT a ternary operator

I guess this is not exactly news, but IIf does not provide short circuiting.  Both the True and False paths are evaluated.  I’m sure I ran into this before and just forgot about it, but I wanted to post this so hopefully I will remember not to use IIf as a null check for an object b/c it will pass/use the Null despite the result of the boolean evaluation:

Dim agencyId As Integer = _
    IIf(agencyCode IsNot Nothing, SomeMethodThatNoLikeNull(agencyCode), 0)

 

1 comment:

Brian said...

Yes, most people dont realize that one until the code has been running and the empty object comes through and the exceptions start to flow.

I never use the IIf syntax, I only use AndAlso,OrElse. these will shortcut, so you can put your nothing check first and the comparison second.