null (C# 參考)

關鍵字 null 是一個字面值,代表一個空參考,也就是不指向任何物件的空參考。 null 是參考型別變數的預設值。 普通值型別不能是空值,除非是 可為空值型別

C# 語言參考資料記錄了 C# 語言最新版本。 同時也包含即將推出語言版本公開預覽功能的初步文件。

文件中標示了語言最近三個版本或目前公開預覽版中首次引入的任何功能。

小提示

欲查詢某功能何時首次在 C# 中引入,請參閱 C# 語言版本歷史的條目。

下列範例示範 null 關鍵詞的一些行為:

class Program
{
    class MyClass
    {
        public static void MyMethod() { }
    }

    static void Main()
    {
        // Set a breakpoint here to see that mc = null.
        // However, the compiler considers it "unassigned."
        // and generates a compiler error if you try to
        // use the variable.
        MyClass mc;

        // Now the variable can be used, but...
        mc = null;

        // ... a method call on a null object raises
        // a run-time NullReferenceException.
        // Uncomment the following line to see for yourself.
        // mc.MyMethod();

        // Now mc has a value.
        mc = new MyClass();

        // You can call its method.
        MyClass.MyMethod();

        // Set mc to null again. The object it referenced
        // is no longer accessible and can now be garbage-collected.
        mc = null;

        // A null string is not the same as an empty string.
        string s = null;
        string t = string.Empty; // Logically the same as ""

        // Equals applied to any null object returns false.
        Console.WriteLine($"t.Equals(s) is {t.Equals(s)}");

        // Equality operator also returns false when one
        // operand is null.
        Console.WriteLine($"Empty string {(s == t ? "equals" : "does not equal")} null string");

        // Returns true.
        Console.WriteLine($"null == null is {null == null}");

        // A value type cannot be null
        // int i = null; // Compiler error!

        // Use a nullable value type instead:
        int? i = null;

        // Keep the console window open in debug mode.
    }
}

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和使用方式的最終來源。

另請參閱