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 and 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. We introduced you to methods in Chapter 1, and you’ve been using the Main( ) and WriteLine( ) methods extensively in the past three chapters. When the compiler reaches the WriteLine( ) call, the compiler stops execution in the Main( ) method and branches to the WriteLine( ) method, which exists elsewhere in the .NET Framework. When the WriteLine( ) method completes its execution—or returns—execution picks up in the original method on the line just below the branch point (the line where the WriteLine( ) method was called).

Conditional branching is more complicated. Methods can branch based on the evaluation of certain conditions that occur at runtime. ...

Get Learning C# 3.0 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.