multiple conditions in if then statements

A

Analysis&Solutions

When evaluating multiple conditions in an if then statement,
all other languages I've dealt with act in an efficient manner;
if the first condition fails, save time by not evaluating
subsequent conditions.

This is helpful when working with arrays. The first condition
can act as a safeguard against exceeding the bounds of the array
in the second condition.

Unfortunately, the VB engine doesn't work that way...


Dim i As Integer = 1
Dim a() As String = New String() {"zero", "one", "two"}
Dim bound As Integer = UBound(a)

' This is okay because i is within bounds.
If i <= bound And a(i) = "one" Then
MsgBox(i & " is less than " & bound)
End If

' The second condition is evaluated even though the first
' condition is false, resulting in the following error:
' "Index was outside the bounds of the array."
i = 6
If i <= bound And a(i) = "one" Then
' DUH!
End If
 
T

Tom Shelton

Analysis&Solutions laid this down on his screen :
When evaluating multiple conditions in an if then statement,
all other languages I've dealt with act in an efficient manner;
if the first condition fails, save time by not evaluating
subsequent conditions.

This is helpful when working with arrays. The first condition
can act as a safeguard against exceeding the bounds of the array
in the second condition.

Unfortunately, the VB engine doesn't work that way...


Dim i As Integer = 1
Dim a() As String = New String() {"zero", "one", "two"}
Dim bound As Integer = UBound(a)

' This is okay because i is within bounds.
If i <= bound And a(i) = "one" Then
MsgBox(i & " is less than " & bound)
End If

' The second condition is evaluated even though the first
' condition is false, resulting in the following error:
' "Index was outside the bounds of the array."
i = 6
If i <= bound And a(i) = "one" Then
' DUH!
End If

AndAlso, OrElse

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top