Delen via


null (C#-verwijzing)

Het null trefwoord is een letterlijke waarde die een null-verwijzing vertegenwoordigt, een verwijzing die niet naar een object verwijst. null is de standaardwaarde van variabelen van het verwijzingstype. Gewone waardetypen kunnen niet null zijn, met uitzondering van typen null-waarden.

De C#-taalreferentiedocumenten beschrijven de meest recent uitgebrachte versie van de C#-taal. Het bevat ook de eerste documentatie voor functies in openbare previews voor de aanstaande taalrelease.

De documentatie identificeert alle functies die voor het eerst zijn geïntroduceerd in de laatste drie versies van de taal of in de huidige openbare previews.

Aanbeveling

Raadpleeg het artikel over de versiegeschiedenis van de C#-taal om te achterhalen wanneer een functie voor het eerst is geïntroduceerd in C#.

In het volgende voorbeeld ziet u een aantal gedragingen van het trefwoord 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#-taalspecificatie

Zie de C#-taalspecificatievoor meer informatie. De taalspecificatie is de definitieve bron voor de C#-syntaxis en het gebruik.

Zie ook