170 Part II Programming Fundamentals
of an If statement makes logical sense—why should Visual Basic continue to evaluate the If
statement if both conditions cannot be True?
The OrElse operator works in a similar fashion. Consider an If statement that has two
conditions that are connected by an OrElse operator. For the statements of the If structure
to be executed, at least one condition must evaluate to True. If the first condition evaluates
to True, Visual Basic begins to execute the statements in the If structure immediately, without
testing the second condition.
Here’s an example of the short-circuit situation in Visual Basic, a simple routine that uses
an If statement and an AndAlso operator to test two conditions and display the message
“Inside If” if both conditions are True:
Dim Number As Integer = 0
If Number = 1 AndAlso MsgBox("Second condition test") Then
MsgBox("Inside If")
Else
MsgBox("Inside Else")
End If
The MsgBox function itself is used as the second conditional test, which is somewhat unusual,
but the strange syntax is completely valid and gives us a perfect opportunity to see how
short-circuiting works up close. The text “Second condition test” appears in a message
box only if the Number variable is set to 1; otherwise, the AndAlso operator short-circuits
the If statement, and the second condition isn’t evaluated. If you actually try this code,
remember that it’s for demonstration purposes only—you wouldn’t want to use MsgBox
with this syntax as a test because it doesn’t really test anything. But by changing the Number
variable from 0 to 1 and back, you can get a good idea of how the AndAlso statement and
short-circuiting work.
Here’s a second example of how short-circuiting functions in Visual Basic when two
conditions are evaluated using the AndAlso operator. This time, a more complex conditional
test (7 / HumanAge <= 1) is used after the AndAlso operator to determine what some
people call the “dog age” of a person:
Dim HumanAge As Integer
HumanAge = 7
'One year for a dog is seven years for a human
If HumanAge <> 0 AndAlso 7 / HumanAge <= 1 Then
MsgBox("You are at least one dog year old")
Else
MsgBox("You are less than one dog year old")
End If
As part of a larger program that determines the so-called dog age of a person by dividing
his or her current age by 7, this bare-bones routine tries to determine whether the value
in the HumanAge integer variable is at least 7. (If you haven’t heard the concept of “dog
age” before, bear with me—following this logic, a 28-year-old person would be four dog