VB.NET's Logical Operators AndAlso and OrElse

This Quick Tip Shows You What They Can Do

software developer and Computer script
Juhari Muhade / Getty Images

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.

What's New

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.

Example

Suppose you're coding a test of a calculation result like this:

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.

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.

Format
mla apa chicago
Your Citation
Mabbutt, Dan. "VB.NET's Logical Operators AndAlso and OrElse." ThoughtCo, Aug. 28, 2020, thoughtco.com/vbnets-logical-operators-andalso-and-orelse-3424268. Mabbutt, Dan. (2020, August 28). VB.NET's Logical Operators AndAlso and OrElse. Retrieved from https://www.thoughtco.com/vbnets-logical-operators-andalso-and-orelse-3424268 Mabbutt, Dan. "VB.NET's Logical Operators AndAlso and OrElse." ThoughtCo. https://www.thoughtco.com/vbnets-logical-operators-andalso-and-orelse-3424268 (accessed March 29, 2024).