Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

?: operator - the ternary conditional operator

  • 2023-07-25
Feedback

In this article

The conditional operator?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates totrue orfalse, as the following example shows:

string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ? "Cold." : "Perfect!";Console.WriteLine(GetWeatherDisplay(15));  // output: Cold.Console.WriteLine(GetWeatherDisplay(27));  // output: Perfect!

As the preceding example shows, the syntax for the conditional operator is as follows:

condition ? consequent : alternative

Thecondition expression must evaluate totrue orfalse. Ifcondition evaluates totrue, theconsequent expression is evaluated, and its result becomes the result of the operation. Ifcondition evaluates tofalse, thealternative expression is evaluated, and its result becomes the result of the operation. Onlyconsequent oralternative is evaluated. Conditional expressions are target-typed. That is, if a target type of a conditional expression is known, the types ofconsequent andalternative must be implicitly convertible to the target type, as the following example shows:

var rand = new Random();var condition = rand.NextDouble() > 0.5;int? x = condition ? 12 : null;IEnumerable<int> xs = x is null ? new List<int>() { 0, 1 } : new int[] { 2, 3 };

If a target type of a conditional expression is unknown (for example, when you use thevar keyword) or the type ofconsequent andalternative must be the same or there must be an implicit conversion from one type to the other:

var rand = new Random();var condition = rand.NextDouble() > 0.5;var x = condition ? 12 : (int?)null;

The conditional operator is right-associative, that is, an expression of the form

a ? b : c ? d : e

is evaluated as

a ? b : (c ? d : e)

Tip

You can use the following mnemonic device to remember how the conditional operator is evaluated:

is this condition true ? yes : no

Conditional ref expression

A conditional ref expression conditionally returns a variable reference, as the following example shows:

int[] smallArray = {1, 2, 3, 4, 5};int[] largeArray = {10, 20, 30, 40, 50};int index = 7;ref int refValue = ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]);refValue = 0;index = 2;((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]) = 100;Console.WriteLine(string.Join(" ", smallArray));Console.WriteLine(string.Join(" ", largeArray));// Output:// 1 2 100 4 5// 10 20 0 40 50

You canref assign the result of a conditional ref expression, use it as areference return or pass it as aref,out,in, orref readonlymethod parameter. You can also assign to the result of a conditional ref expression, as the preceding example shows.

The syntax for a conditional ref expression is as follows:

condition ? ref consequent : ref alternative

Like the conditional operator, a conditional ref expression evaluates only one of the two expressions: eitherconsequent oralternative.

In a conditional ref expression, the type ofconsequent andalternative must be the same. Conditional ref expressions aren't target-typed.

Conditional operator and anif statement

Use of the conditional operator instead of anif statement might result in more concise code in cases when you need conditionally to compute a value. The following example demonstrates two ways to classify an integer as negative or nonnegative:

int input = new Random().Next(-5, 5);string classify;if (input >= 0){    classify = "nonnegative";}else{    classify = "negative";}classify = (input >= 0) ? "nonnegative" : "negative";

Operator overloadability

A user-defined type can't overload the conditional operator.

C# language specification

For more information, see theConditional operator section of theC# language specification.

Specifications for newer features are:

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo