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

后端 未结 5 874
天涯浪人
天涯浪人 2020-11-29 07:17

I recently learned of the IIF(A,B,C) function. I\'m a long time VB/VB.NET Coder who recently spent a lot of time coming up to speed in SQL coding.

One (obvious) commo

5条回答
  •  有刺的猬
    2020-11-29 07:42

    [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.

提交回复
热议问题