Share via


?? 演算子 (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()
    {
        int? x = null;

        // Set y to the value of x if x is NOT null; otherwise, 
        // if x = null, set y to -1. 
        int y = x ?? -1;

        // Assign i to return value of the method if the method's result 
        // is NOT null; otherwise, if the result is null, set i to the 
        // default value of int. 
        int i = GetNullableInt() ?? default(int);

        string s = GetStringValue();
        // Display the value of s if s is NOT null; otherwise,  
        // display the string "Unspecified".
        Console.WriteLine(s ?? "Unspecified");
    }
}

参照

関連項目

C# 演算子

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

概念

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

その他の技術情報

C# リファレンス

What Exactly Does 'Lifted' mean? ('Lifted' の正確な意味)