The Conditional Operator


As shown in Syntax Box 8.12 the conditional operator combines three expressions with the two symbols question mark ? and colon :. It will return either the value of ExpressionA or the value of ExpressionB, depending on whether the Boolean expression to the left of the question mark is true or false. If true, the value of ExpressionA is returned; otherwise, the value of ExpressionB is returned.

Syntax Box 8.12 The Conditional Operator

 <Boolean_expression> ? <ExpressionA> : <ExpressionB> 



The conditional operator is the only operator in C# to combine three expressions, so it is also referred to as the ternary operator.

Let's have a look at a couple of examples. The Boolean expression of the following expression is true, so the value of the overall expression is 100.

 (3 < 10) ? 100 : 200 

In the next line

 (3 > 20) ? 200 : 300 

the value of the expression is 300 because (3 > 20) is false, causing the value after the colon to be returned.

Sometimes a simple if-else statement can be substituted with the conditional operator and create shorter more compact code. Consider the following if-else statement

 if (distance1 > distance2)       maxDistance = distance1; else       maxDistance = distance2; 

It says that if distance1 is greater than distance2, assign distance1 to maxDistance; otherwise, assign distance2 to maxDistance. This can be expressed in one line by using the conditional operator:

 maxDistance = (distance1 > distance2) ? distance1 : distance2; 

which, like its if-else statement counterpart, assigns the larger value of distance1 and distance2 to maxDistance.



The conditional operator always returns a value, so it can only be used instead of certain types of if-else statements, such as the one shown in the previous example.


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: