
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
128
|
Chapter 3: Classes and Structures
The ternary operator is able to compact several lines of an if-else statement into a
single expression that can fit easily on a single line. This ternary statement is also
usable inline with a statement or another expression. The following code example
shows the use of the ternary operator inline with an expression:
byte x = (byte)(8 + ((foo == 1) ? 4 : 2));
By examining the order of operator precedence, you can see that the == operator is
evaluated first and then the ternary operator. Depending on the result of the Boolean
expression
foo == 1, the ternary operator will produce either the value 4 or 2. This
value is then added to
8 and assigned to the variable x.
This operator is considered to have right-associative properties, similar to the assign-
ment operators. Because of this, you can get into trouble using ternary expressions as
expressions within other ternary expressions. Consider the following code:
// foo currently equals 1
// Assume that all methods will always return a Boolean true, except for Method3,
// which always returns a Boolean false.
Console.WriteLine(Method1( ) ? Method2( ) : Method3( ) ? Method4( ) : Method5( ));
Which methods will be called? If you started evaluating this expression from the left,
your expression would essentially ...