?: Operator
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is used in an expression of the following form:
cond-expr ? expr1 : expr2
Where:
- cond-expr
- An expression of type bool.
- expr1
- An expression.
- expr2
- An expression.
Remarks
If cond-expr is true, expr1 is evaluated and becomes the result; if cond-expr is false, expr2 is evaluated and becomes the result. Only one of expr1 and expr2 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 sinc 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
a ? b : c ? d : e
is evaluated as
a ? b : (c ? d : e)
not
(a ? b : c) ? d : e
The conditional operator cannot be overloaded.
Example
// cs_operator_conditional.cs
using System;
class Test
{
public static double sinc(double x)
{
return x != 0.0 ? Math.Sin(x)/x : 1.0;
}
public static void Main()
{
Console.WriteLine(sinc(0.2));
Console.WriteLine(sinc(0.1));
Console.WriteLine(sinc(0.0));
}
}
Output
0.993346653975306 0.998334166468282 1