OrElse Operator (Visual Basic)
Performs short-circuiting inclusive logical disjunction on two expressions.
result = expression1 OrElse expression2
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending on the result of another expression. If the result of the first expression evaluated determines the final result of the operation, there is no need to evaluate the second expression, because it cannot change the final result. Short-circuiting can improve performance if the bypassed expression is complex, or if it involves procedure calls.
If either or both expressions evaluate to
True. The following table illustrates how
result is determined.
||The value of
OrElse operator is defined only for the Boolean Data Type. Visual Basic converts each operand as necessary to
Boolean and performs the operation entirely in
Boolean. If you assign the result to a numeric type, Visual Basic converts it from
Boolean to that type. This could produce unexpected behavior. For example,
5 OrElse 12 results in
–1 when converted to
The Or Operator and the IsTrue Operator can be overloaded, which means that a class or structure can redefine their behavior when an operand has the type of that class or structure. Overloading the
IsTrue operators affects the behavior of the
OrElse operator. If your code uses
OrElse on a class or structure that overloads
IsTrue, be sure you understand their redefined behavior. For more information, see Operator Procedures.
The following 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.
Dim a As Integer = 10 Dim b As Integer = 8 Dim c As Integer = 6 Dim firstCheck, secondCheck, thirdCheck As Boolean firstCheck = a > b OrElse b > c secondCheck = b > a OrElse b > c thirdCheck = b > a OrElse c > b
The preceding example produces results of
False respectively. In the calculation of
firstCheck, the second expression is not evaluated because the first is already
True. However, the second expression is evaluated in the calculation of
The following example shows an
Then statement containing two procedure calls. If the first call returns
True, the second procedure is not called. This could produce unexpected results if the second procedure performs important tasks that should always be performed when this section of the code runs.
If testFunction(5) = True OrElse otherFunction(4) = True Then ' If testFunction(5) is True, otherFunction(4) is not called. ' Insert code to be executed. End If