Lesson 11 / 25

Nullable Types and Null Safety

Use nullable value types and nullable reference types to prevent NullReferenceException.

Making null explicit

Value types cannot be null, so C# offers nullable value types: int? (short for Nullable<int>) can hold a number or null, with .HasValue and .Value. For reference types, null was always allowed, which made NullReferenceException the most common .NET bug. Nullable reference types (enabled with <Nullable>enable</Nullable>, on by default in new projects) change the rules at compile time: string means should never be null and string? means may be null. The compiler tracks null state and warns when you dereference a maybe-null value or assign null to a non-nullable one. Operators help: ?. (null-conditional: customer?.Address?.City), ?? (null-coalescing: a fallback value), ??= (assign if null) and ! (the null-forgiving operator, which silences a warning and should be rare). C# 14 also allows ?. on the left of an assignment.

Handling null deliberately

Warnings point out every place a null could slip through.

#nullable enable

string? FindNickname(Dictionary<string, string> nicknames, string name) =>
    nicknames.TryGetValue(name, out var nick) ? nick : null;

var nicknames = new Dictionary<string, string> { ["Rahul"] = "Rocky" };

string? nick = FindNickname(nicknames, "Priya");
Console.WriteLine(nick.Length);            // warning CS8602: possible null dereference
Console.WriteLine(nick?.Length ?? 0);      // safe

string display = nick ?? "no nickname";

int? age = null;
int years = age ?? 18;

List<string>? cache = null;
cache ??= new List<string>();               // assign only if null

Treat nullable warnings as errors

Nullable warnings are only useful if you act on them. Add <WarningsAsErrors>nullable</WarningsAsErrors> to new projects, and use ! only when you can prove the value is not null and the compiler cannot.

Quick check: With nullable reference types enabled, what does `string?` mean?

  • A string that is always null
  • A string variable that may be null, so the compiler checks uses of it
  • A nullable value type
  • A string stored on the stack
Answer

A string variable that may be null, so the compiler checks uses of it — The ? annotation marks a reference as possibly null, enabling compile-time null-safety warnings.