16.5. Branching


Visual Basic 2005 statements are evaluated in order. The compiler starts at the beginning of a statement list and makes its way to the bottom. This would be entirely straightforward, and terribly limiting, were it not for branching .

Methods are executed from top to bottom. The compiler reads each line of code in turn, and executes one line after another. This continues in sequence until the method branches.

There are two ways a method can branch: unconditionally or conditionally. We'll look at each of these in turn.

16.5.1. Unconditional Branching Statements

The most common way to branch is by calling a method. This is an unconditional branch.

You call a method by writing its name. For example:

 Method1(  )  'invokes Method1 

It is also legal to call a VB.NET method with the optional keyword call:

 call Method1(  ) 

If you do use call on a function, the return value is discarded. There is no advantage to this syntax, and it isn't used in this book.


Every time the compiler encounters a method call, it stops execution in the current method and branches to the newly called method. When that method returns, execution picks up in the original method on the line just below the method call, as illustrated schematically in Figure 16-2.

Figure 16-2. Branching schematic


In Figure 16-2, execution begins in Main. Statements 1 and 2 execute and then the compiler sees a call to Method1. Program execution branches to the start of Method1, where its first three statements are executed. At the call to Method1A execution again branches, this time to the start of Method1A.

The four statements in Method1A are executed and Method1A returns. Execution resumes on the first statement after the method call in Method1 (Statement 4). Execution continues until Method1 ends, at which time execution resumes back in Main at Statement 3. At the call to Method2, execution again branches; all the statements in Method2 execute and then Main resumes at Statement 4. When Main ends, the program itself ends.

You can see the effect of method calls in Example 16-5. Execution begins in Main, but branches to a method named SomeMethod. The WriteLine statements in each method assist you in seeing where you are in the code as the program executes.

Example 16-5. Calling a method
 Option Strict On Option Explicit On Module Module1    Sub Main(  )       Console.WriteLine("In Main! Calling SomeMethod...")       SomeMethod(  )       Console.WriteLine("Back in Main.")    End Sub 'Main    Sub SomeMethod(  )       Console.WriteLine("Greetings from SomeMethod!")    End Sub 'SomeMethod End Module Output: In Main! Calling SomeMethod... Greetings from SomeMethod! Back in Main. 

Program flow begins in Main and proceeds until SomeMethod is invoked (invoking a method is sometimes referred to as "calling " the method). At that point, program flow branches to the method. When the method completes, program flow resumes at the next line after the call to that method.

Another way to create an unconditional branch is with one of the unconditional branch keywords: goto, exit, return, or throw.


16.5.2. Conditional Branching Statements

While method calls cause unconditional branching, often you will want to branch within a method depending on a condition that you evaluate while the program is running. This is known as conditional branching.

Conditional branching statements allow you to write logic, such as "If you are over 25, then you may rent a car."

16.5.2.1. If statements

The simplest branching statement is If. An If statement branches based on a condition. The condition is a Boolean expression.An expression is a statement that evaluates to a value. A Boolean expression evaluates to true or False.

An If statement says: if the condition evaluates to true, then execute the statement, otherwise, skip it. The formal description of an if statement is:

 If expressionThen    statements End If 

An alternative one-line version is:

 If expression Then statement 

The use of the If statement is illustrated in Example 16-6.

Example 16-6. The If statement
 Option Strict On Module Module1    Sub Main(  )       Dim valueOne As Integer = 10       Dim valueTwo As Integer = 20       Dim valueThree As Integer = 30       Console.WriteLine("Testing valueOne against valueTwo...")       If valueOne > valueTwo Then          Console.WriteLine( _              "ValueOne: {0} larger than ValueTwo: {1}", _               valueOne, valueTwo)       End If       Console.WriteLine("Testing valueThree against valueTwo...")       If valueThree > valueTwo Then          Console.WriteLine( _              "ValueThree: {0} larger than ValueTwo: {1}", _               valueThree, valueTwo)       End If       Console.WriteLine("Testing is valueTwo > 15 (one line)...")       If valueTwo > 15 Then Console.WriteLine("Yes it is")    End Sub 'Main End Module Output: Testing valueOne against valueTwo... Testing valueThree against valueTwo... ValueThree: 30 larger than ValueTwo: 20 Testing is valueTwo > 15 (one line)... Yes it is 

In this simple program, you declare three variables, valueOne, valueTwo, and valueThree. In the first If statement, you test whether valueOne is greater than valueTwo.

 If valueOne > valueTwo Then    Console.WriteLine( _        "ValueOne: {0} larger than ValueTwo: {1}", valueOne, valueTwo) End If 

Because valueOne is less than valueTwo, this If statement fails (the condition returns False), and the body of the If statement (the statements between the If and the End If) never executes.

The test for greater than uses the greater-than operator (>), which is discussed in detail later in this chapter.


You then test whether valueThree is greater than valueTwo:

 If valueThree > valueTwo Then    Console.WriteLine( _        "ValueThree: {0} larger than ValueTwo: {1}", valueThree, valueTwo) End If 

Since valueThree (30) is greater than valueTwo (20), the test returns TRue and thus the statement executes. The statement in this case is the call to WriteLine( ), shown in bold.

Finally, Example 16-6 uses a one-line If statement to test whether valueTwo is greater than 15. Since this evaluates to true, the statement that follows executes, and the words "Yes it is" are displayed.

 If valueTwo > 15 Then Console.WriteLine("Yes it is") 

The output reflects that the first If statement fails, but the second and third succeed:

 Testing valueOne against valueTwo... Testing valueThree against valueTwo... ValueThree: 30 larger than ValueTwo: 20 Testing is valueTwo > 15 (one line)... Yes it is 

Many Visual Basic 2005 developers avoid the single line If statement because it can be confusing and difficult to maintain.


16.5.2.2. If...Else statements

Often you will find that you want to take one set of actions when the condition tests TRue, and a different set of actions when the condition tests False. This allows you to write logic such as "If you are over 25, then you may rent a car; otherwise, you must take the train."

The otherwise portion of the logic is executed in the else statement. For example, you can modify Example 16-6 to print an appropriate message whether or not valueOne is greater than valueTwo, as shown in Example 16-7.

Example 16-7. The Else clause
 Option Strict On Option Explicit On Module Module1    Sub Main(  )       Dim valueOne As Integer = 10       Dim valueTwo As Integer = 20       Dim valueThree As Integer = 30       Console.WriteLine("Testing valueOne against valueTwo...")       If valueOne > valueTwo Then          Console.WriteLine( _              "ValueOne: {0} larger than ValueTwo: {1}", valueOne, valueTwo)       Else          Console.WriteLine( _             "Nope, ValueOne: {0} is NOT larger than valueTwo: {1}", _              valueOne, valueTwo)       End If    End Sub 'Main End Module Output: Testing valueOne against valueTwo... Nope, ValueOne: 10 is NOT larger than valueTwo: 20 

Because the test in the If statement fails (valueOne is not larger than valueTwo), the body of the If statement is skipped and the body of the Else statement is executed. Had the test succeeded, the If statement body would execute and the body of the Else statement would be skipped.

It is possible, and not uncommon, to nest If statements one within another, to handle complex conditions. It is also common to evaluate a sequence of expressions with the ElseIf construct. The first If/ElseIf statement to evaluate true will have its statements executed (and no others will even be evaluated). If none of the statements evaluates true, the final Else clause is executed.

16.5.3. Select Case Statements

Nested If statements and long sequences of ElseIf statements are hard to read, maintain, and debug. When you have a complex set of choices to make, the Select Case statement is a more powerful alternative. The logic of a Select Case statement is to "pick a matching value and act accordingly."

 Select [ Case ] testExpression [ Case expressionList    [ statements ] ] [ Case Else    [ else statements] ] End Select 

It is easiest to understand this construct in the context of an example, as shown in Example 16-8.

Example 16-8. Select Case
 Option Strict On Module Module1    Sub Main(  )       Dim targetInteger As Integer = 15       Select Case targetInteger          Case 5             Console.WriteLine("5")          Case 10             Console.WriteLine("10")          Case 15             Console.WriteLine("15!")          Case Else             Console.WriteLine("Value not found")       End Select    End Sub 'Main End Module Output: 15! 

In Example 16-8, a value (15) is assigned to targetInteger. The Select Case statement tests for the values 5, 10 and 15. If one matches, the associated statement is executed. The output shows that the value 15 matched, and the associated statement was executed, displaying the value. If none of the values matched, the Else select statement would be executed.

16.5.3.1. Checking for a range of values

You can check for a range of values (e.g., Case 10 To 14).

You are not restricted to just testing for a numeric value. You can also test for String values, and you can test ranges of string values, examining whether a target value fits alphabetically within the range (e.g., Case "Alpha To Lambda").

A single Case statement can test for more than one criterion: just separate them by commas:

 Case "Fred", "Joe", Is < "Alpha"    Console.WriteLine("Joe or Fred or < Alpha") 

This case will match the strings "Fred" and "Joe" as well as any string that comes alphabetically before "Alpha."



Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net