?? 演算子 (C# リファレンス)

?? 演算子は null 合体演算子と呼ばれ、null 許容値型および参照型の既定値を定義するために使用します。 左側のオペランドが null 値でない場合にはこのオペランドを返し、null 値である場合には右側のオペランドを返します。

解説

null 許容型は、値を指定するか、未定義にしておくことができます。 ?? 演算子は、null 非許容型に対して null 許容型が割り当てられているときに返す既定値を定義します。 ?? 演算子を使用せずに、null 非許容値型に対して null 許容値型を割り当てると、コンパイル時にエラーが発生します。 null 許容値型が定義されていない場合にキャストを使用すると、InvalidOperationException 例外がスローされます。

詳細については、「null 許容型 (C# プログラミング ガイド)」を参照してください。

両方の引数が定数である場合でも、?? 演算子の結果は定数と見なされません。

使用例

class NullCoalesce
{
    static int? GetNullableInt()
    {
        return null;
    }

    static string GetStringValue()
    {
        return null;
    }

    static void Main()
    {
        // ?? operator example.
        int? x = null;

        // y = x, unless x is null, in which case y = -1.
        int y = x ?? -1;

        // Assign i to return value of method, unless
        // return value is null, in which case assign
        // default value of int to i.
        int i = GetNullableInt() ?? default(int);

        string s = GetStringValue();
        // ?? also works with reference types. 
        // Display contents of s, unless s is null, 
        // in which case display "Unspecified".
        Console.WriteLine(s ?? "Unspecified");
    }
}

参照

参照

C# 演算子

null 許容型 (C# プログラミング ガイド)

概念

C# プログラミング ガイド

その他の技術情報

C# リファレンス

What Exactly Does 'Lifted' mean? (「リフト」の正確な意味)