The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form
condition ? first_expression : second_expression;
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.
class ConditionalOp
{
static double sinc(double x)
{
return x != 0.0 ? Math.Sin(x) / x : 1.0;
}
static void Main()
{
Console.WriteLine(sinc(0.2));
Console.WriteLine(sinc(0.1));
Console.WriteLine(sinc(0.0));
}
}
/*
Output:
0.993346653975306
0.998334166468282
1
*/
Concepts
Reference
Other Resources