Conditional Branching Statements

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

C# provides a number of constructs that allow you to write conditional branches into your programs; these constructs are described in the following sections.

if Statements

The simplest branching statement is if. An if statement says, “if a particular condition is true, then execute the statement; otherwise skip it.” The condition is a Boolean expression. An expression is a statement that evaluates to a value, and a Boolean expression evaluates to either true or false.

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. Note that Statement1 can actually be a block of statements within braces, as illustrated in Example 6-2.

Tip

Anywhere in C# that you are expected to provide a statement, you can instead provide a block of statements within braces. (See the sidebar Brace Styles later in this chapter.)

Example 6-2. The if statement

using System; ...

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