# ?: 运算符（C# 参考）?: operator (C# reference)

condition ? consequent : alternative


condition 表达式的计算结果必须为 truefalseThe condition expression must evaluate to true or false. condition 的计算结果为 true，将计算 consequent，其结果成为运算结果。If condition evaluates to true, the consequent expression is evaluated, and its result becomes the result of the operation. condition 的计算结果为 false，将计算 alternative，其结果成为运算结果。If condition evaluates to false, the alternative expression is evaluated, and its result becomes the result of the operation. 只会计算 consequentalternativeOnly consequent or alternative is evaluated.

consequentalternative 的类型必须相同，或者必须存在从一种类型到另一种类型的隐式转换。The type of consequent and alternative must be the same, or there must be an implicit conversion from one type to the other.

a ? b : c ? d : e


a ? b : (c ? d : e)


is this condition true ? yes : no


double sinc(double x) => x != 0.0 ? Math.Sin(x) / x : 1;

Console.WriteLine(sinc(0.1));
Console.WriteLine(sinc(0.0));
// Output:
// 0.998334166468282
// 1


## ref 条件表达式Conditional ref expression

ref 条件表达式的语法如下所示：The syntax for the conditional ref expression is as follows:

condition ? ref consequent : ref alternative


ref 条件表达式与原始的条件运算符相似，仅计算两个表达式其中之一：consequentalternativeLike the original conditional operator, the conditional ref expression evaluates only one of the two expressions: either consequent or alternative.

var smallArray = new int[] { 1, 2, 3, 4, 5 };
var largeArray = new int[] { 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


## 条件运算符和 if..else 语句Conditional operator and an if..else statement

int input = new Random().Next(-5, 5);

string classify;
if (input >= 0)
{
classify = "nonnegative";
}
else
{
classify = "negative";
}

classify = (input >= 0) ? "nonnegative" : "negative";