Collection initialisation using iif() throws ArgumentNullException

157 views Asked by At

Can anyone tell me why this gives an error at run-time:

Dim mightBeNothing As List(Of String) = Nothing
Dim a As List(Of String) = IIf(mightBeNothing Is Nothing, New List(Of String)(), New List(Of String)(mightBeNothing))

I am getting ArgumentNullException on the second line. If I replace the last part with:

Dim a As List(Of String) = IIf(mightBeNothing Is Nothing, New List(Of String)(), New List(Of String)())

It works - but the constructor New List(Of String)(mightBeNothing) will never be called if mightBeNothing is nothing, so what is the issue?

3

There are 3 answers

3
Jay On BEST ANSWER

the IIf function does not use short-circuit evaluation. So it will always evaluate everything, even if mightBeNothing is nothing.

MSDN on the subject.

0
Tim On

First, collection initializers aren't supported prior to VB.NET 10.

Having said that, the first example is passing in a null (Nothing) value for the third argument. The IIf Function always evaluate all three arguments, regardless of the true/false state of the first argument. I believe that is why you are receiving the ArgumentNullException.

In the second case, none of the arguments are Nothing so it works, but doesn't give you the desired results.

I would recommend using an If Else:

Dim mightBeNothing As List(Of String) = Nothing
Dim a As List(Of String)

If mightBeNothing Is Nothing Then
    a = New List(Of String)
Else
    a = New List(Of String)
    a.Add(mightBeNothing)
End If
0
BenR On

Try using the IF operator instead of IIF. It will short-circuit. See this article on MSDN