VB.NET features two logical operators that help make your programming ... well ... more logical. The new operators are AndAlso and OrElse and they add a lot to the old And and Or operators.
AndAlso and OrElse have some properties that enhance your code in ways that previous VB versions couldn't match. They offer advantages in two general categories:
- You can avoid executing part of a logical expression to avoid problems.
- You can optimize code by not executing any more of a compound expression than required.
AndAlso and OrElse are pretty much like And and Or except that they will "short circuit" an expression once the outcome is guaranteed.
Suppose you're coding a test of a calculation result like this:
Dim Value1 As Integer = 1 Dim Value2 As Integer = 1 Dim Value3 As Integer = 0 Dim a As Integer = 1 Dim b As Integer = 1 If a < Value1 And b < (Value2 \ Value3) Then Debug.WriteLine("Inside If") End If
The If expression generates a "divide by zero" error in VB 6 because Value3 is zero. (But see the Quick Tip on divide by zero for more on that.) It could be that the cases that result in Value3 being zero are very rare and only occur when you're enjoying a vacation a thousand miles away so you can be called back to fix the program in an emergency mode. (Hey! It happens!)
Let's recode the program as a .NET program using AndAlso and see what happens.
If a > Value1 AndAlso b > (Value2 \ Value3) Then
Click Here to display the illustration
Click the Back button on your browser to return
After changing And to AndAlso, the program works! The reason is that the last part of the compound If condition - (value 2 \ value3) - is never actually executed. When you use AndAlso, VB.NET knows that the expression can't succeed once it is determined that the first part of the condition - a is not greater than Value1 - is false. So VB.NET stops evaluating the expression right there. A similar example could be constructed using OrElse.
This analysis also suggests how you can add some efficiency to your code by arranging a compound logical expression correctly. If you place the expression that is most likely to be false in the leftmost position when using AndAlso, you can prevent execution cycles from being used to evaluate the rightmost expression. In a single test, it wouldn't make enough difference to be worth even thinking about. But if your test is inside a loop of some kind and is executed zillions of times, it could make a big difference.
Knowing about these two new VB .NET logical operators can help you avoid very subtle errors or achieve subtle efficiencies.