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:
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?
An optional parameterA string that may be nullA nullable charA required string
Show answer
Answer: A string that may be null