C# Tutorial · Advanced C# · Lesson 19 of 22

C# Nullable Reference Types

string vs string?, null warnings and safe null handling.

Nullable reference types

With nullable reference types enabled (the default in new projects), string means "never null" and string? means "may be null". The compiler warns when you might dereference null:

Example 1
static string? FindEmail(int id) => id == 1 ? "[email protected]" : null;

string? email = FindEmail(2);
// Console.WriteLine(email.Length);   // warning CS8602: possible null dereference
Console.WriteLine(email?.Length ?? 0);
if (email is not null)
    Console.WriteLine(email.ToUpper());
Console.WriteLine(FindEmail(1)!.Length);  // ! tells the compiler "trust me"

int? maybe = null;
Console.WriteLine($"{maybe.HasValue} {maybe.GetValueOrDefault(5)}");

Output

0
15
False 5

Run this on your computer — see “Get Started” for setup.

Value types use the same syntax: int? is a nullable int with .HasValue and .Value.

Test yourself

What does string? mean?

  1. An optional parameter
  2. A string that may be null
  3. A nullable char
  4. A required string
Show answer

Answer: A string that may be null