Using VB.NET IIF I get NullReferenceException

I am doing a little debugging, and so I want to log the eventArgs value

I have a simple line that basically does:

logLine = "e.Value: " + IIf(e.Value Is Nothing, "", e.Value.ToString())

The way I understand the IIF function, if the e.Value is Nothing (null) then it should return the empty string, if not it should return the .ToString of the value. I am, however getting a NullReferenceException. This doesn’t make sense to me.

Any idea’s?

3 thoughts on “Using VB.NET IIF I get NullReferenceException

  1. user

    VB does not do short-circuiting evaluation in Iif. In your case, e.Value.ToString() is being evaluated no matter whether e.Value is nothing.

    Reply
  2. user

    This is the expected behaviour.

    IIF is a function; therefore the parameters for the function will be evaluated before sending it to the function.

    In contrast, the ternary operator in C# is a language construct that prevents the evaluation of the second parameter if the expression of the ternary is true.

    Reply
  3. user

    IIf is an actual function, so all arguments get evaluated. The If keyword was added to VB.NET 2008 to provide the short-circuit functionality you’re expecting.

    Try

    logLine = "e.Value: " + If(e.Value Is Nothing, "", e.Value.ToString())
    
    Reply

Leave a Reply

Your email address will not be published.