Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

11.17.1 Short-circuiting Logical Operators

Visual Studio .NET 2003

The AndAlso and OrElse operators, which are the short-circuiting logical operators, are only defined for the type Boolean. Because of their short circuiting behavior, the second operand is not evaluated at run time if the operator result is known after evaluating the first operand.

The short-circuiting logical operators are evaluated as follows:

  • If the first operand in an AndAlso operation evaluates to False, the expression returns False. Otherwise, the second operand is evaluated and a logical And operation is performed on the two results.
  • If the first operand in an OrElse operation evaluates to True, the expression returns True. Otherwise, the second operand is evaluated and a logical Or operation is performed on its two results.

When evaluating the AndAlso or OrElse operators, the first operand is evaluated only once, and the second operand is either not evaluated or evaluated exactly once. For example, consider the following code:

Imports System

Module Test
    Function TrueValue() As Boolean
        Console.Write(" True")
        Return True
    End Function

    Function FalseValue() As Boolean
        Console.Write(" False")
        Return False
    End Function

    Sub Main()
        Console.Write("And:")
        If FalseValue() And TrueValue() Then
        End If
        Console.WriteLine()

        Console.Write("Or:")
        If TrueValue() Or FalseValue() Then
        End If
        Console.WriteLine()

        Console.Write("AndAlso:")
        If FalseValue() AndAlso TrueValue() Then
        End If
        Console.WriteLine()

        Console.WriteLine("OrElse:")
        If TrueValue() OrElse FalseValue() Then
        End If
        Console.WriteLine()
    End Sub
End Module

It prints the following result:

And: False True
Or: True False
AndAlso: False
OrElse: True
ShortCircuitLogicalOperatorExpression ::=
   Expression AndAlso Expression |
   Expression OrElse Expression

See Also

11.12.1 Operator Precedence and Associativity | 11.12.2 Object Operands | 11.12.3 Operator Resolution | 11.13 Arithmetic Operators | 11.14 Relational Operators | 11.15 Like Operator | 11.16 Concatenation Operator | Operators Listed by Functionality (Visual Basic Language Reference)

Show:
© 2015 Microsoft