null (C#-Referenz)null (C# Reference)

Das Schlüsselwort null ist ein Literal, das einen NULL-Verweis darstellt, der auf kein Objekt verweist.The null keyword is a literal that represents a null reference, one that does not refer to any object. null ist der Standardwert einer Verweistypvariablen.null is the default value of reference-type variables. Normale Verweistypen dürfen nicht NULL sein.Ordinary value types cannot be null. C# 2.0 hat jedoch auf NULL festlegbare Werttypen eingeführt.However, C# 2.0 introduced nullable value types. Siehe Nullable-Typen.See Nullable Types.

Im folgenden Beispiel werden einige Verhalten des NULL-Schlüsselworts gezeigt:The following example demonstrates some behaviors of the null keyword:

class Program
    class MyClass
        public void MyMethod() { }

    static void Main(string[] args)
        // 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.

        // 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.
        bool b = (t.Equals(s));

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

        // Returns true.
        Console.WriteLine("null == null is {0}", 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.
        System.Console.WriteLine("Press any key to exit.");


C#-ProgrammiersprachenspezifikationC# Language Specification

Weitere Informationen erhalten Sie unter C#-Sprachspezifikation.For more information, see the C# Language Specification. Die Sprachspezifikation ist die verbindliche Quelle für die Syntax und Verwendung von C#.The language specification is the definitive source for C# syntax and usage.

Siehe auchSee Also

C#-ReferenzC# Reference
C#-ProgrammierhandbuchC# Programming Guide
C#-SchlüsselwörterC# Keywords
LiteralschlüsselwörterLiteral Keywords
Tabelle für StandardwerteDefault Values Table