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.

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

Tip

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.

Branching schematic

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 ...

Get Programming Visual Basic 2005 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.