49

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 Answers 3

94

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())
Sign up to request clarification or add additional context in comments.

3 Comments

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

2 Comments

Do you know a solution then ?
Yes, use If as the selected answer suggests.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.