Bagikan melalui


null (Referensi C#)

Kata null kunci adalah literal yang mewakili referensi null, yang tidak merujuk ke objek apa pun. null adalah nilai default variabel jenis referensi. Jenis nilai biasa tidak boleh null, kecuali untuk jenis nilai yang dapat diubah ke null.

Referensi bahasa C# mendokumentasikan versi bahasa C# yang paling baru dirilis. Ini juga berisi dokumentasi awal untuk fitur dalam pratinjau publik untuk rilis bahasa yang akan datang.

Dokumentasi mengidentifikasi fitur apa pun yang pertama kali diperkenalkan dalam tiga versi terakhir bahasa atau dalam pratinjau publik saat ini.

Petunjuk / Saran

Untuk menemukan kapan fitur pertama kali diperkenalkan di C#, lihat artikel tentang riwayat versi bahasa C#.

Contoh berikut menunjukkan beberapa perilaku kata kunci 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.
    }
}

Spesifikasi bahasa C#

Untuk informasi selengkapnya, lihat Spesifikasi Bahasa C#. Spesifikasi bahasa adalah sumber definitif untuk sintaks dan penggunaan C#.

Lihat juga