Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 555
Nathan Koop Avatar asked Jan 09 '09 17:01

Nathan Koop


People also ask

What is NullReferenceException in VB net?

A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.

Is null or nothing in VB net?

What is VB.NET null ? A null value is a value that doesnt refer to any object. Strings are reference types and can be equal to the null value like any other reference type. VB.NET uses the keyword Nothing for null values.

Is null in VB?

The Null value indicates that the Variant contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It's also not the same as a zero-length string (""), which is sometimes referred to as a null string.

Is nothing in VB net?

"IsNothing is intended to work on reference types. A value type cannot hold a value of Nothing and reverts to its default value if you assign Nothing [...] IsNothing always returns False." But Nothing "Represents the default value of any data type. [...]


2 Answers

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()) 
like image 116
bdukes Avatar answered Sep 26 '22 20:09

bdukes


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.

like image 30
Chris Farmer Avatar answered Sep 25 '22 20:09

Chris Farmer