← Back to C# Course | Chapter 15: Modern C# Features | Lesson 5 of 6

Nullable Reference Types (Concept)

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)

markup
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);
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.