Is there any situation where Or
is better to use than OrElse
?
If not, why don't they just "upgrade" the internal code?
The only reason to use Or
is when you want bitwise arithmetic, i.e. you want to manipulate the bits in a number:
Sub SetBit(value As Integer, Bit As Integer)
value = value Or (1 << Bit)
End Sub
This kind is the only case appropriate for Or
. In all other cases (i.e. when using Boolean logic), use OrElse
.
Despite their similar names, Or
and OrElse
are semantically quite distinct operations which should not be confused with each other. It just so happens to be that the internal representation of Boolean
s makes it possible to use bitwise Or
to achieve a similar (but not the same) effect to OrElse
. (Old versions of BASIC and VB – before .NET – exploited this relationship by only providing an Or
operation, no OrElse
.)
You should always use OrElse instead of Or, except when doing bit-wise arithmetic.
OrElse is a short-circuiting comparison, meaning it will not evaluate the second clause if the first was true. This is extremely useful, because you will often want clauses which could fail without shortcircuiting (eg. x is nothing OrElse not x.HasSomeProperty).
The reason it is not possible to automatically upgrade all 'Or's as 'OrElse's is because the evaluation of the second clause may be important. For example, I could write "True Or SomeBooleanMethodWhichMightThrowAnEception()". Changing that Or to an OrElse would change the meaning of the program.
Edit: This code is evil; I merely added this answer to indicate that this is possible.
Another case would be to use Or when evaluating expressions that perform some sort of side effect that must occur:
Sub DoSomething()
Dim succeeded As Boolean
succeeded = FirstThing() Or SecondThing() Or ThirdThing()
If succeeded Then
' Do something here
End If
End Sub
In this case FirstThing, SecondThing, and ThirdThing are methods that must be executed as a whole whether any of them fail or not, while accumulating a success value. If you used OrElse then if FirstThing or SecondThing fail, then the operations behind the failing method wouldn't occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With