Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

`#nullable enable` and the `T?` annotation for reference types

Enable nullable reference annotations and compiler warnings. See how a null check affects flow analysis and why `string?` does not work the same way as `int?`.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

#nullable enable
// T? denotes a nullable reference when T is a reference type.
static void ShowLength(string? text)
{
    if (text is not null)
        System.Console.WriteLine(text.Length);
}
#nullable restore

#nullable enable turns on both nullable annotations and nullable warnings. It applies from that point in the source file until another directive changes those settings or the file ends. #nullable restore uses the project settings again, not the previous settings in the file.

When T is a reference type, T? says that null is allowed, while plain T says that a non-null reference is expected. string and string? are the same runtime type and cannot distinguish overloads. The compiler adds no automatic null check, so accessing a member through a null reference can still throw NullReferenceException.

Flow analysis tracks whether a reference might be null at each point in the code. Accessing text.Length before the check would trigger CS8602. The text is null check and early return leave only the non-null path to the later access. Writing text! can suppress the warning, but it neither checks nor changes the value.

Contrast this with int?, which is shorthand for System.Nullable<int>, a distinct value type that can also represent the absence of a value. string? does not wrap the reference in System.Nullable<T>.

Examples

#nullable enable
using System;

PrintLength(null);
PrintLength("Ada");

static void PrintLength(string? text)
{
    // Console.WriteLine(text.Length); // CS8602
    if (text is null)
    {
        Console.WriteLine("No text");
        return;
    }

    Console.WriteLine(text.Length);
}

Result

No text
3

The first call prints `No text` and returns before reading `Length`. The second prints `3`. To see `CS8602`, uncomment the first `text.Length` access in `PrintLength` and build without running.

Related lessons

  • C# · Lesson 17 · Intermediate · Version: 2

Sources