Nullable Reference Types (Concept)
In this page:
Nullable Reference Types (Concept)
C# 8 introduced nullable reference type annotations (string? meaning "may be null", string meaning "should not be null") to catch accidental null-reference bugs at compile time. Since this needs a modern Roslyn-based compiler and project setting to enforce, this example instead demonstrates the underlying discipline manually: explicit null checks before use, which is exactly what the nullable-reference-types feature nudges the compiler to warn you about automatically.
Warning: Nullable reference type annotations are compile-time hints only — they do not stop null from being assigned at runtime, they just produce warnings.
Example: Nullable Reference Types (Concept)
using System;
class Program
{
static void PrintLength(string value)
{
if (value == null)
{
Console.WriteLine("Value was null, skipping");
return;
}
Console.WriteLine(value.Length);
}
static void Main(string[] args)
{
PrintLength("hello");
PrintLength(null);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: