0

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?

BenR
  • 11,296
  • 3
  • 28
  • 47
Flash
  • 15,945
  • 13
  • 70
  • 98

3 Answers3

2

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

MSDN on the subject.

Jay
  • 5,897
  • 1
  • 25
  • 28
  • Thanks, I changed iif() to if() and it works as expected. Not sure why you would want iif not to short circuit, I just assumed it did. – Flash Jan 31 '12 at 01:29
  • IIf is a tricky little beast - I don't do a lot of VB.NET now, but a few years ago I was and it threw me for a loop because I assumed it would work like the C# ternary operator (?:). – Tim Jan 31 '12 at 01:32
  • 1
    Iif doesn't short-circuit because it's a plain function, not an operator like If. – Meta-Knight Jan 31 '12 at 01:39
1

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
Tim
  • 28,212
  • 8
  • 63
  • 76
1

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

BenR
  • 11,296
  • 3
  • 28
  • 47