views:

2948

answers:

3

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?

+2  A: 

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
+2  A: 

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 language construct that prevents the evaluation of the second parameter if the expression of the ternary is true.

Philip Fourie
+12  A: 

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
Also: If() is typesafe. IIf() is not.
Joel Coehoorn