Skip to content
AgileLogics
5 min read

Nullable Types & Null Safety

Prerequisites: LINQ

Modern C# (nullable reference types, on by default in new projects) distinguishes a type that can be null from one that can't, directly in the type system — the compiler warns if you might be dereferencing null.

string name = "Ada";       // can never be null
string? nickname = null;    // explicitly CAN be null

int? age = null;            // Nullable<int> — value types need this wrapper
Console.WriteLine(age ?? 0); // 0 — the null-coalescing operator

string? city = null;
Console.WriteLine(city?.Length); // null — null-conditional, no exception

This is a genuine, compile-time-enforced defense against the "null reference exception" class of bug that both Java and C#'s earlier years were notorious for.

Common mistakes

  • Using the ! "null-forgiving" operator (name!) to silence a nullable warning without actually confirming the value can't be null at that point — this just turns a compile-time warning back into a potential runtime crash.