?: 演算子 - 三項条件演算子

条件演算子 ?: は、三項条件演算子とも呼ばれ、ブール式を評価し、ブール式の評価結果 (true または false) に応じて、2 つの式のいずれかの結果を返します。次の例を参照してください。

string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ? "Cold." : "Perfect!";

Console.WriteLine(GetWeatherDisplay(15));  // output: Cold.
Console.WriteLine(GetWeatherDisplay(27));  // output: Perfect!

前の例で示したように、条件演算子の構文は次のようになります。

condition ? consequent : alternative

condition 式は true または false と評価する必要があります。 conditiontrue と評価された場合は、consequent 式が評価され、その結果が演算の結果になります。 conditionfalse と評価された場合は、alternative 式が評価され、その結果が演算の結果になります。 consequent または alternative のみが評価されます。 条件式はターゲット型です。 つまり、条件式のターゲット型がわかっている場合、次の例に示すように、consequentalternative の型は、暗黙的にターゲット型に変換できる必要があります。

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 };

条件式のターゲット型が不明な場合 (たとえば、var キーワードを使用する場合)、または consequentalternative の型を同にする必要がある場合、またはある型から別の型に暗黙的に変換される必要がある場合、次のようにします。

var rand = new Random();
var condition = rand.NextDouble() > 0.5;

var x = condition ? 12 : (int?)null;

条件演算子は右結合です。つまり、次の形式の式があるとします。

a ? b : c ? d : e

これが次のように評価されます。

a ? b : (c ? d : e)

ヒント

次のニーモニック デバイスを使用して、条件演算子の評価方法を思い出すことができます。

is this condition true ? yes : no

ref 条件式

次の例に示すように、条件 ref 式は変数参照を条件付きで返します:

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

条件付き ref 式の結果を ref 割り当てたり、参照の戻り値 として使用したり、refoutin、またはref readonlyメソッド パラメーターとして渡したりできます。 前の例に示すように、条件 ref 式の結果に代入することもできます。

ref 条件式の構文は次のとおりです。

condition ? ref consequent : ref alternative

ref 条件式では、元の条件演算子と同じように、2 つの式 (consequent または alternative) のいずれかのみが評価されます。

ref 条件式では、consequentalternative の型は同じである必要があります。 ref 条件式は、ターゲット型ではありません。

条件演算子と if ステートメント

if ステートメントではなく条件演算子を使用すると、値の計算を条件付きで実行する必要がある場合に、コードをもっと簡潔にできる可能性があります。 次の例では、整数を負の値または負以外の値に分類するための 2 つの方法を示しています。

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

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

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

演算子のオーバーロード可/不可

ユーザー定義型は条件演算子をオーバーロードできません。

C# 言語仕様

詳細については、「C# 言語仕様」の「条件演算子」セクションを参照してください。

新しい機能の仕様は次のとおりです。

関連項目