{see's Rachels post} AndAlso...

Seeing Rachels post a moment ago reminded me that I had a blog entry regarding OrElse/AndAlso that I have been meaning to post... Recently, I commented to a friend that, some developers might appreciate some "improvements" to the exception handling that is offered by .NET, specifically I was thinking of something like this:
 Try
 .
 .
 Catch
     .
     .
     TryHarder
     .
     .
     Catch
          .
          . 
          OhPlease
Anyway, he's not a .NET guy and came back with: "does TryHarder actually exist in .NET??" :-) That kind of cracked me up, but, also reminded me of those other funny words... No, but VB has OrElse and AndAlso and they are just as silly. They are basically shortcut-evaluation versions of "Or" and "And". For example:
'-----------------------------
 Class Person
  Public Name As String = "Fred"
 End Class
'-----------------------------
 Dim obj As Person

 ' This would throw an exception 
 If TypeOf (obj) Is Person And obj.Name = "Fred" Then
  MsgBox( obj.Name )
 End If
 ' This would be fine 
 If TypeOf (obj) Is Person AndAlso obj.Name = "Fred" Then
  MsgBox( obj.Name )
 End If
'-----------------------------

The OrElse keyword *always* cracks me up because I can imagine the compiler emitting an "OrElseWhat?" exception if it fails :-)

For those (other) non-.NET'tish folk: The | operator of C/C++/C#/Java/JavaScript is the same as the VB.NET OR operator. And the || operator is the same as VB.NET's OrElse operator.

4 Comments

  • hehe, "TryHarder". I like that one.



    I always imagine the compiler getting ticked off with me for using AndAlso, since English-wise they mean the same thing, but AndAlso is a longer to write (and thus compile) version.

  • Re: OrElse/AndAlso, for those who remember the .NET Framework Beta1 (or was it even in Beta2), intially VB.NET's Or and And operators were short-circuiting, but the old VB guard complained citing lack of backward compatability and difficulty in porting.



    Darren said: "The | operator of C/C++/C#/Java/JavaScript is the same as the VB.NET OR operator. And the || operator is the same as VB.NET's OrElse operator"



    I don't think this is true. The | operator is for a bit-wise OR in those languages - that is, it takes two *integers* and returns a bit-wise integer OR value. || is a logical or, and is short-circuiting in languages like C#/C/C++/etc. (Namely, it takes in two *booleans* and returns a boolean value.)

  • I think they ARE the same...



    AND & OR are bitwise in VB

    ANDALSO & ORELSE are boolean in VB

  • Steve,

    Yes, but AND & OR are also boolean in VB. They can be either bitwise or boolean due to the way booleans are represented. There's no need to do AndAlso or OrElse for a boolean compare, and in fact if you don't want short circuiting of your operators, it's a good way to accomplish that.

Comments have been disabled for this content.