Permalink
Fetching contributors…
Cannot retrieve contributors at this time
64 lines (52 sloc) 2.48 KB
title ms.date ms.prod ms.technology ms.topic f1_keywords dev_langs helpviewer_keywords ms.assetid caps.latest.revision author ms.author
?: Operator (C# Reference)
07/20/2015
.net
devlang-csharp
article
?:_CSharpKeyword
?_CSharpKeyword
:_CSharpKeyword
CSharp
?: operator [C#]
conditional operator (?:) [C#]
e83a17f1-7500-48ba-8bee-2fbc4c847af4
23
BillWagner
wiwagn

?: Operator (C# Reference)

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

condition ? first_expression : second_expression;  

Remarks

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to classify an integer as positive or negative.

int input = Convert.ToInt32(Console.ReadLine());  
string classify;  
  
// if-else construction.  
if (input > 0)  
    classify = "positive";  
else  
    classify = "negative";  
  
// ?: conditional operator.  
classify = (input > 0) ? "positive" : "negative";  

The conditional operator is right-associative. The expression a ? b : c ? d : e is evaluated as a ? b : (c ? d : e), not as (a ? b : c) ? d : e.

The conditional operator cannot be overloaded.

Example

[!code-cscsRefOperators#41]

See Also

C# Reference
C# Programming Guide
C# Operators
if-else
?. and ?Operators
?? Operator