A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/../keywords/null below:

null keyword - C# reference

null (C# Reference)

In this article

The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables. Ordinary value types cannot be null, except for nullable value types.

The following example demonstrates some behaviors of the null keyword:

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# language specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also

Collaborate with us on GitHub

The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.

Additional resources

In this article

Was this page helpful?


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4