tags:

views:

384

answers:

3

Hi all !

My doubt is about OR and ORELSE. There is any situation where OR is better to use than ORELSE ? And if not, why they don't just "upgrade" de internal code ?

Cheers !!

+5  A: 

The only solution 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.)

Konrad Rudolph
Konrad's got it right but if you want to read more about it from the previous maintainer of the VB language you can check out Paul Vick's article http://www.panopticoncentral.net/archive/2003/08/18/179.aspx
Chris Haas
+1  A: 

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.

Erik Forbes
I hope you realize that this code is evil. If you want the side effects, then make the comparisons sequentially. The above code is quite well obfuscated: I for one would immediately think that it’s a bug and not intended.
Konrad Rudolph
+1 because your answer is correct, but I agree with Konrad, it's not a good practice to do so!
Meta-Knight
Don't get me wrong - I'm not advocating this in the slightest!
Erik Forbes
+1  A: 

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.

Strilanc