Visual Basic Operators: ‘AndAlso’ & ‘OrElse’

Since I’ve mostly been using C# for the past few years, I sometimes get confused when I come across a Visual Basic application and have to distinguish between the newer operators (OrElse, AndALso vs Or, And)

Operator: OrElse

This example uses the OrElse operator to perform logical disjunction on two expressions. The result is a Boolean value that represents whether either of the two expressions is true. If the first expression is True, the second is not evaluated. If the first expression is false then the second expression is evaluated.

Dim A As Integer = 10
Dim B As Integer = 8
Dim C As Integer = 6
Dim myCheck As Boolean
myCheck = A > B OrElse B > C ‘ True. Second expression is not evaluated.
myCheck = B > A OrElse B > C ‘ True. Second expression is evaluated.
myCheck = B > A OrElse C > B ‘ False.

Operator: Or (if either expression evaluates to true then true will be returned)

Dim A As Integer = 10
Dim B As Integer = 8
Dim C As Integer = 6
Dim myCheck As Boolean
myCheck = A > B Or B > C ‘ Returns True.
myCheck = B > A Or B > C ‘ Returns True.
myCheck = B > A Or C > B ‘ Returns False.

Operator: AndAlso (if first expression evaluates to false then second expression is not evaluated)

Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b AndAlso b > c ‘ Returns True.
secondCheck = b > a AndAlso b > c ‘ Returns False
thirdCheck = a > b AndAlso c > b ‘ Returns False

Operator: And (both expressions are evaluated)

Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck As Boolean
firstCheck = a > b And b > c ‘ Returns True.
secondCheck = b > a And b > c ‘ Returns False

Ideally, the short circuit operations, you’re saving on the extra condition check when the first one is satisfied (OrElse) or not satisfied (AndAlso). So these should give you better performance in general.

OrElse: http://msdn.microsoft.com/en-us/library/ea1sssb2.aspx
AndAlso: http://msdn.microsoft.com/en-us/library/cb8x3kfz.aspx