預設值運算式:產生預設值

預設值運算式 會產生型別 的預設值。 預設值運算式有兩種:預設運算子呼叫和預設常值

您也可以在switch陳述式使用 default 關鍵字作為預設案例標籤。

預設運算子

default 運算子的引數必須是型別名稱或型別參數,如下列範例所示:

Console.WriteLine(default(int));  // output: 0
Console.WriteLine(default(object) is null);  // output: True

void DisplayDefaultOf<T>()
{
    var val = default(T);
    Console.WriteLine($"Default value of {typeof(T)} is {(val == null ? "null" : val.ToString())}.");
}

DisplayDefaultOf<int?>();
DisplayDefaultOf<System.Numerics.Complex>();
DisplayDefaultOf<System.Collections.Generic.List<int>>();
// Output:
// Default value of System.Nullable`1[System.Int32] is null.
// Default value of System.Numerics.Complex is (0, 0).
// Default value of System.Collections.Generic.List`1[System.Int32] is null.

預設常值

當編譯器可以推斷運算式型別時,您可以使用 default 常值來產生型別的預設值。 default 常值運算式會產生與對default(T) 運算式相同的值,其中 T 是推斷出來的型別。 在下列任一情況中,您都可以使用 default 常值:

下列範例會示範 default 常值的使用方式:

T[] InitializeArray<T>(int length, T initialValue = default)
{
    if (length < 0)
    {
        throw new ArgumentOutOfRangeException(nameof(length), "Array length must be nonnegative.");
    }

    var array = new T[length];
    for (var i = 0; i < length; i++)
    {
        array[i] = initialValue;
    }
    return array;
}

void Display<T>(T[] values) => Console.WriteLine($"[ {string.Join(", ", values)} ]");

Display(InitializeArray<int>(3));  // output: [ 0, 0, 0 ]
Display(InitializeArray<bool>(4, default));  // output: [ False, False, False, False ]

System.Numerics.Complex fillValue = default;
Display(InitializeArray(3, fillValue));  // output: [ (0, 0), (0, 0), (0, 0) ]

提示

使用 .NET 樣式規則 IDE0034 指定程式碼基底中使用 default 常值的喜好設定。

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格預設值運算式一節。

另請參閱