Information Technology Reference
In-Depth Information
Figure 8-8 compares the two forms shown in the example.
Figure 8-8.
The conditional operator versus if...else
For example, the following code uses the conditional operator three times—once in each
of the
WriteLine
statements. In the first instance, it returns either the value of
x
or the value of
y
. In the second two instances, it returns either the empty string or the string “
not
.”
int x = 10, y = 9;
int HighVal = (x > y) // Condition
? x // Expression 1
: y; // Expression 2
Console.WriteLine("HighVal: {0}\n", HighVal);
Console.WriteLine("x is{0} greater than y",
x > y // Condition
? "" // Expression 1
: " not"); // Expression 2
y = 11;
Console.WriteLine("x is{0} greater than y",
x > y // Condition
? "" // Expression 1
: " not"); // Expression 2
This code produces the following output:
HighVal: 10
x is greater than y
x is not greater than y
■
Note
The
if...else
statement is a flow-of-control
statement
. It should be used for
doing
one or the
other of two
actions
. The conditional expression is an
expression
. It should be used for
returning
one or
the other of two
values
.