Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vb.net

Is there any situation where Or is better to use than OrElse?

If not, why don't they just "upgrade" the internal code?

like image 471
Thiago Bernabé Avatar asked Jan 08 '10 13:01

Thiago Bernabé


3 Answers

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 Booleans 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.)

like image 61
Konrad Rudolph Avatar answered Nov 12 '22 11:11

Konrad Rudolph


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.

like image 3
Craig Gidney Avatar answered Nov 12 '22 12:11

Craig Gidney


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.

like image 2
Erik Forbes Avatar answered Nov 12 '22 11:11

Erik Forbes