NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

?: Operator

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
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

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.99334665397530608
0.99833416646828155
1

See Also

C# Operators | CLR 7.12 Conditional operator