Team LiB   Previous Section   Next Section

Chapter 6. Branching

A method is, essentially, a mini-program within your larger program. It is a set of statements that execute one after the other, as in the following:

void MyMethod()
{
   int a;  // declare an integer
   a = 5;  // assign it a value
   console.WriteLine("a: {0}", a);  // display the value
}

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. Branching means that the current method is interrupted temporarily and a new method or routine is executed; when that new method or routine finishes, the original method picks up where it left off. A method can branch in either of two ways: unconditionally or conditionally.

As the name implies, unconditional branching happens every time the program is run. An unconditional branch happens, for example, whenever the compiler encounters a new method call. The compiler stops execution in the current method and branches to the newly called method. When the newly called method returns (i.e., completes its execution), execution picks up in the original method on the line just below the line where the new method was called.

Conditional branching is more complicated. Methods can branch based on the evaluation of certain conditions that occur at runtime. For instance, you might create a branch that will calculate an employee's federal withholding tax only when their earnings are greater than the minimum taxable by law. C# provides a number of statements that support conditional branching, such as if, else, and switch. The use of these statements is discussed later in this chapter.

A second way that methods break out of their mindless step-by-step processing of instructions is by looping. A loop causes the method to repeat a set of steps until some condition is met (e.g., "Keep asking for input until the user tells you to stop or until you receive ten values"). C# provides many statements for looping, including for, while, and do...while, which are also discussed in this chapter.

    Team LiB   Previous Section   Next Section