English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C# includes a decision-making operator ? :, called the conditional operator or ternary operator. It is a shorthand for if-Abbreviation of else condition.
Syntax:
condition ? statement 1 : statement 2
The ternary operator starts from a boolean condition. If the value of condition is true, it will execute the statement after ? 1 Statement, otherwise the second statement after : will be executed.
The following example demonstrates the ternary operator.
int x = 20, y = 10; var result = x > y ? "x大于y" : "x小于y"; Console.WriteLine(result);
x大于y
The condition expression x > y returns true, so the first statement after ? will be executed.
The following statement executes the second statement.
int x = 10, y = 100; var result = x > y ? "x大于y" : "x小于y"; Console.WriteLine(result);
x小于y
Therefore, the ternary operator is a shorthand for if-else statements. The above example can be rewritten using if-else conditions as follows.
int x = 10, y = 100; if (x > y){ Console.WriteLine("x大于y"); }else{ Console.WriteLine("x小于y"); }
x大于y
Nested ternary operator is implemented by using the condition expression as the second statement.
int x = 10, y = 100; string result = x > y ? "x大于y": ; x < y ? "x is less than y" : x == y ? "x equals y" : "No result" Console.WriteLine(result);
The ternary operator is right-associative. The evaluation of the expression a ? b : c ? d : e results in a ? b : (c ? d : e), not (a ? b : c) ? d : e.
var x = 2, y = 10; var result = x * 3 y ? x : y > z ? y : z; Console.WriteLine(result);