?: Operator
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

?: Operator (C# Reference)

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

a ? b : c ? d : e

is evaluated as

a ? b : (c ? d : e)


(a ? b : c) ? d : e

The conditional operator cannot be overloaded.

// cs_operator_conditional.cs
using System;
class MainClass
    static double sinc(double x) 
        return x != 0.0 ? Math.Sin(x)/x : 1.0;

    static void Main() 

© 2015 Microsoft