Saturday, July 28, 2007

VB .NET New Logical Operators AndAlso and OrElse

Excerpts from an article written by Dan Mabbutt entitled VB .NET New Logical Operators.

VB .NET features two new logical operators that help make your programming ... well ... more logical. The new operators are AndAlso and OrElse and they generally replace the VB 6 operators And and Or (but they do much more!).

The old VB 6 And and Or are still present in VB .NET. If you decide that they're what you need your program, go ahead and use them. They work the same way they used to work.

But AndAlso and OrElse have some properties that enhance your code in ways that VB 6 can'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.

Knowing about these two new VB .NET logical operators can help you avoid very subtle errors or achieve subtle efficiencies.