If condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.
Calculations that might otherwise require an if-else construction can be expressed more concisely and elegantly with the conditional operator. For example, to avoid a division by zero in the calculation of the sin function you could write either
|
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
|
or, using the conditional operator,
|
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
|
The conditional operator is right-associative, so an expression of the form
is evaluated as
not
The conditional operator cannot be overloaded.