# ?: 運算子 (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

condition ? ref consequent : ref 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";