Visual Basic .NET Shortcircuited And

I think that AndAlso is just so much more elegant than the old Visual Basic 6 And.

if (condition1) AndAlso (condition2) then
..............
end if

is so much nicer than

if (condition1) then
     if (condition2) then
................
     end if
end if

 

4 Comments

  • It's more elegant/readable, gives better performance, and is less likely to introduce bugs.



    I've actually seen people who use the non-short-circuit nature of AND/Or to actually do processing (ie, even if the first part of the AND was false, they relied on the 2nd part to process to do some work) which is really not intuitive and can quickly lead to bugs...

  • Plus I've found that if you use AndAlso and OrElse everywhere for boolean logic, it makes your bitwise Ands and Ors stand out as well.

  • Hmm you are missing the point.



    AndAlso is there because of lazy evaluation.



    With the AndAlso you will have lazyevaluation.



    Your examples do not have the same behaviour AFAIK.



    So change the example to show what you could accomplish with that keyword like :



    VB6:



    If (Not obj Is Nothing)

    If (obj.datamember = 10) Then

    ...

    End If

    End If



    VB.NET:



    If (Not obj Is Nothing) AndAlso (obj.datamember = 10) Then

    ...

    End If

  • Wallym you are right on the money as is Wedgebert... I had VB6 nested if statements x levels deep to simulate short-circuiting that now go on one line (same for OrElse). Karl has a good point and it is the reason when giving this advice to newbies you should immediately follow it with "Don't do a global find replace!"



    Ramon, how is your example different to the one given above?

Comments have been disabled for this content.