Saturday, November 23, 2019
AndAlso and OrElse VB.NET Basic Logical Operators
AndAlso and OrElse VB.NET Basic Logical Operators 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. Whats New AndAlso and OrElse have some properties that enhance your code in ways that previous VB versions couldnt 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 youre 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 youre enjoying a vacation a thousand miles away so you can be called back to fix the program in an emergency mode. (Hey! It happens!) Lets 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 cant 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 wouldnt 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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.