Chapter 5. Branching
All the statements in your program execute in order. Unfortunately, that’s not very useful, unless you want your program to do exactly the same thing every time you run it. In fact, often you won’t want to execute all the code, but rather you’ll want the program to do one thing if a variable has a certain value, and something different if the variable has another value. That means you need to be able to cause your program to pick and choose which statements to execute based on conditions that change as the program runs. This process is called branching, and there are two ways to accomplish it: unconditionally or conditionally.
As the name implies, unconditional branching happens every time the branch point is reached. 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 (completes its execution), execution picks up in the original method on the line just below the branch point (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 ...
Get Learning C# 2005, 2nd Edition 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.