Using Short-Circuit Condition Evaluation in VB using AndAlso and OrElse

02-07-2012

Normally, a programming language stops evaluating a composite condition when it finds one of following scenarios.

(Condition 1) AND (Condition 2)

Since the above composite condition to evaluate to true, both condition 1 and condition 2 have to evaluate to TRUE.

If the condition 1 evaluates to FALSE then it is obvious that the whole condition is going to evaluate to FALSE Regardless of the condition 2.

Therefore, usually programming languages avoids evaluating the condition 2 to be efficient.

This is same for OR condition

(Condition 1) OR (Condition 2)

If the Condition 1 evaluates to TRUE then the composite condition will be TRUE regardless of the Condition 2 So the programming language can avoid processing the Condition 2

However, this is not straightforward in Visual Basic (6 through to .Net)

If you use following condition, VB compiler will evaluate both conditions:

Student foreignStudent ' foreignStudent is equal to nothing as it's not being initialized yet

IF (foreignStudent isNot Nothing) And (foreignStudent.Country.Equals("Sri Lanka")) THEN
   MSGBOX("Student is from Sri Lanka")
END IF

Theoretically, above should evaluate to False as the first condition is FALSE however, in VB this code will throw an exception because foreignStudent.Country.Equals(“Sri Lanka”) cannot be performed as the foreignStudent object is not initialized (is Nothing).

Solution:
VB provides a method to specifically mention when you need to utilize this short-circuit mechanism.

Simply use AndAlso and OrElse instead of And and Else relatively.

So the updated code for the above requirement would be

Student foreignStudent ' foreignStudent is equal to nothing as it's not being initialized yet

IF (foreignStudent isNot Nothing) AndAlso
(foreignStudent.Country.Equals("Sri Lanka")) THEN
   MSGBOX("Student is from Sri Lanka")
END IF

This code will not throw and exception when the foreignStudent is not initialized.

Hope this helped!

Menol
ILT

Leave a comment