Conditional Branching Statements

Although methods branch unconditionally, 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 years old, then you may rent a car.” This is where the comparison operators you learned about in Chapter 4 become really useful.

C# provides a number of constructs that allow you to write conditional branches into your programs, including the if, else, and switch statements.

if Statements

The simplest branching statement is if. An if statement says, “If a particular condition is true, then execute the following statement; otherwise, skip it.” The condition is a Boolean expression. As you learned in Chapters Chapter 3 and Chapter 4, a Boolean expression evaluates to either true or false, which makes it a perfect fit for the if statement.

The formal description of an if statement is:

if (expression)  Statement1

This is the kind of description of the if statement you are likely to find in your compiler documentation. It shows you that the if statement takes an expression (a statement that returns a value) in parentheses, and executes Statement1 if the expression evaluates true. Statement1 doesn’t have to be just one statement—it can actually be a block of statements within braces. As long as you include the braces, the compiler treats your code as just one statement. Example 5-2 ...

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.