Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
C# Reference
C# Operators
 ?: Operator
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Language Reference
?: Operator (C# Reference)

Updated: November 2007

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)

not

(a ? b : c) ? d : e

The conditional operator cannot be overloaded.

C#
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
*/

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker