共用方式為


?? 運算子 (C# 參考)

更新:2007 年 11 月

?? 運算子稱為 null 聯合運算子,用來定義可為 null 的實值型別和參考型別的預設值。運算子如果不是 null 就會傳回左方運算元,否則傳回右運算元。

備註

可為 null 的型別 (Nullable Type) 可以包含值,也可以是尚未定義。?? 運算子會定義當可為 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# 程式設計手冊

參考

C# 運算子

可為 Null 的型別 (C# 程式設計手冊)

其他資源

C# 參考

「增益」究竟是什麼意思?(英文)