The conditional operator (?:) returns one of two values depending on a third value. The conditional operator is used in an expression of the following form:
cond-expr ? expr1 : expr2
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.
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)); } }
0.99334665397530608 0.99833416646828155 1
C# Operators | CLR 7.12 Conditional operator