5

I am having a weird problem. IIf is messing up when I am working with an array. Apparently it is checking my else statement even though it isn't activated. Here is some code that demonstrates the issue:

'works
 Dim test As String = "bleh"
 If values.Length < 6 Then
   test = "200"
 Else
   test = values(5)
 End If

 'throws indexoutofrange exception
 Dim itemLimit As String = IIf(values.Length < 6, "200", values(5))
Phil
  • 95
  • 1
  • 4

2 Answers2

9

The Iif operator doesn't implement short circuiting and will evaluate both the true and false case. If you want a short-circuit version then use If.

Dim itemLimit As String = If(values.Length < 6, "200", values(5))
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Thanks! You provided the problem & a solution. My only question is what is the point of IIF if it evaluates both the true and false case? – Phil Mar 30 '11 at 23:29
  • @Phil `IIf` has been around since at least VB 7 (original release of VB.Net). At that time VB didn't implement short circuiting for the majority of their constructs (`And` / `Or` don't actually short circuit). This function was designed at that time and hence didn't add short circuiting logic – JaredPar Mar 30 '11 at 23:31
2

Have a look at this article: http://www.fmsinc.com/free/newtips/net/nettip33.asp

From the article:

Visual Basic, VBA, and Visual Basic .NET support the IIF function as an alternative to the If...Then...Else statement. Although this may seem like a shortcut, IIF functions differently than If...Then...Else.

IIF must evaluate the entire statement when preparing the argument, which can lead to undesirable side effects.

In other words, your If...Then...Else works because the Else clause isn't being evaluated if the condition fails. The IIf, on the other hand, evaluates all the statements, causing the IndexOutOfBounds exception.

Ender
  • 14,995
  • 8
  • 36
  • 51