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.
The simplest branching statement is
if statement says,
“if a particular condition is true, then execute the
statement; otherwise skip it.” The condition is a
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:
This is the kind of description of the
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.
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; ...