Nullable Reference Types (Concept)
In this page:
string? nullable = null; // may be null
string nonNullable = ""; // should never be null
if (nullable != null)
{
nullable.Length;
}
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.
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
- Thinking
string?prevents nulls at runtime, when it only makes the compiler give warnings; anullcan still get through and throw aNullReferenceException. - Silencing warnings everywhere with the
!null-forgiving operator, which only hides the problem instead of checking for null. - Expecting warnings without enabling nullable context (
<Nullable>enable</Nullable>in the project), so nothing is checked.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: