When is "Or" better to use than "OrElse"?

Is there a situation where Or better to use than OrElse ?

If not, why don't they just “update” the internal code?

+6
source share
3 answers

The only solution to using Or is when you want bitwise arithmetic, i.e. want to manipulate bits in number:

 Sub SetBit(value As Integer, Bit As Integer) value = value Or (1 << Bit) End Sub 

This type is the only case suitable for Or . In all other cases (i.e., using logical logic) use OrElse .

Despite their similar names, Or and OrElse are semantically completely distinct operations that should not be confused with each other. It so happened that the Boolean internal representation allows you to use bitwise Or to achieve a similar (but not the same) effect for OrElse . (Older versions of BASIC and VB — before .NET — used this association only by providing the operation Or , no OrElse .)

+8
source share

You should always use OrElse instead of Or, unless you are doing bit arithmetic.

OrElse is a short circuit, meaning that it will not evaluate the second sentence if the first was true. This is very useful because you'll often want clauses that can fail without a short circuit (for example, x is nothing ORElse, not x.HasSomeProperty).

The reason it’s not possible to automatically update all OrElse’s updates is that evaluating the second sentence can be important. For example, I could write "True or SomeBooleanMethodWhichMightThrowAnEception ()". Changing this or OrElse will change the value of the program.

+3
source share

Edit : this code is evil ; I simply added this answer to indicate that this is possible.

Another case would be to use or in evaluating expressions that perform some kind of side effect that should happen:

 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 should be executed as a whole, regardless of whether any of them fail or not, when the success value is accumulated. If you used OrElse, then if FirstThing or SecondThing failed, then the operations underlying the failure method will not be performed.

+2
source share

All Articles