Wednesday, January 4, 2012

Conditional and Loop Statements

Visual Basic .NET supports all the conditional and loop statements supported by its predecessors—that is, the If and Select conditional blocks and the For, Do, and While loop statements. Nevertheless, Visual Basic .NET offers some new features in this area as well, and Visual Basic .NET 2003 adds a new way to declare the controlling variable in For and For Each loops.



Short-Circuit Evaluation with AndAlso and OrElse Operators

Short-circuit evaluation allows you to avoid the unnecessary evaluation of Boolean subexpressions if they wouldn’t affect the value of the main expression. Let’s see a simple example:
CODES:

If the n1 variable is 0 or negative, the entire expression can only be False, whether the subexpression following the And operator evaluates to True or False. Previous Visual Basic versions always evaluate the entire If expression, so they incur an unnecessary performance hit. Visual Basic .NET lets you produce smarter code using the new AndAlso and OrElse operators, which enforce short-circuit evaluation:
CODES:
This expression is equivalent to the following, more verbose, code:
CODES:
You can have short-circuit evaluation in situations in which you use the Or operator:
CODES:
In this case, if the n1 variable is greater than 0, the entire expression is surely True, so evaluating the second subexpression Log(n2) can be sidestepped. You can enforce this smarter behavior with the new OrElse operator:
CODES:
These new operators also work inside complex Boolean expressions: CODES:

Short-circuit evaluation helps you avoid many run-time errors without writing much code. For example, you can use the following approach to read an array element only if the index is in the valid range: 
CODES:

Here’s another example:
CODES:

The AndAlso operator lets you avoid errors when you check the property of an object variable that might be Nothing: CODES: