Roadmap › C# Language — Basics to Advanced › Module: Types in Depth
Lessons in this course (38)
18. Nullable types and null safety
Intermediate★ Must knowLesson 18 of 38
csharp
int? maybe = null; // Nullable<int>
if (maybe.HasValue) Console.WriteLine(maybe.Value);
int value = maybe ?? -1;
#nullable enable // nullable reference types (C# 8) — on by default in new projects
string name = "x"; // must not be null
string? middle = null; // may be null
Console.WriteLine(middle?.Length); // compiler warns if you dereference without a check
string sure = middle!; // null-forgiving operator — you promise it isn't nullNullable reference types are compile-time warnings only; at runtime a string can still be null if a warning was ignored.