47

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?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Nathan Koop
  • 24,803
  • 25
  • 90
  • 125

3 Answers3

90

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())
bdukes
  • 152,002
  • 23
  • 148
  • 175
  • 7
    Also: If() is typesafe. IIf() is not. – Joel Coehoorn Jan 09 '09 at 17:35
  • I still have problem using the short circuit If with types like Date and Boolean and yet still assigning to a nullable type. For example I want to return 'Nothing' just like above to a Nullable Boolean value using 'If' but it still returns 'False'. Crazy thing when I break the lines out to a If-Else-End If the logic works as expected. – atconway Dec 13 '11 at 20:39
  • 2
    @atconway, apparently `Nothing` in VB is like `default` in C#, rather than `null`, so when used in a context where `Boolean` is the implied type, its value is `False` instead of `null`/`Nothing` as you'd typically think of it (per http://stackoverflow.com/q/1828173/2688). You'll need to cast one side of the `If` to the correct type (e.g. `Boolean?`) to get the desired result. Similarly in C#, you need to cast one side (but it's a compile error if you don't). – bdukes Dec 14 '11 at 20:34
4

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.

Chris Farmer
  • 24,974
  • 34
  • 121
  • 164
3

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.

Philip Fourie
  • 111,587
  • 10
  • 63
  • 83