๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# Nullable Types

A nullable reference type is a reference that is allowed to hold null. The question-mark annotation on the type states that promise in the code.

A null name with fallbacks

The name starts as null. Both print lines fall back to safe values.

using System;

#nullable enable

class Program
{
    static void Main(string[] args)
    {
        string? name = null;
        Console.WriteLine("Name: " + (name ?? "unknown"));
        Console.WriteLine("Length: " + (name?.Length ?? 0));
    }
}

The same lines after assignment

Once the name holds real text, the fallbacks step aside. The real values print.

using System;

#nullable enable

class Program
{
    static void Main(string[] args)
    {
        string? name = null;
        name = "Hana";
        Console.WriteLine("Name: " + (name ?? "unknown"));
        Console.WriteLine("Length: " + (name?.Length ?? 0));
    }
}

A safe call with ?.

The ?. operator skips the call when the word is null. The ?? operator then supplies the printed text.

using System;

#nullable enable

class Program
{
    static void Main(string[] args)
    {
        string? word = null;
        Console.WriteLine(word?.ToUpper() ?? "nothing");
        word = "hi";
        Console.WriteLine(word?.ToUpper() ?? "nothing");
    }
}

Example

using System;

#nullable enable

class Program
{
    static void Main(string[] args)
    {
        string? name = "Hana";
        string? city = null;
        Console.WriteLine("Hello, " + (name ?? "guest"));
        Console.WriteLine("City: " + (city ?? "unknown"));
        Console.WriteLine("City length: " + (city?.Length ?? 0));
    }
}

Key points

  • The #nullable enable line turns on nullable checks for the file.
  • Writing string? declares a string that may hold null.
  • A plain string declares a value that should never be null.
  • The ?? operator gives a fallback when the left side is null.
  • The ?. operator reads a member only when the value is not null.
  • After ?. on a null value, the result is null instead of a crash.
  • Misusing a maybe-null value brings a compiler warning, not an error.

In this example, the name holds text and the city holds null. The greeting prints the real name because the left side of ?? is not null. The city lines use the fallbacks, printing unknown and a length of 0. No line crashes on the null value.

Note

The two operators pair well, as in name?.Length ?? 0.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does `name?.Length ?? 0` give when name is null?