Nullable reference types

Why a string can be null

A reference type in C# may hold null, and a null has no members: a member access on it throws NullReferenceException at run time. That exception is the most common crash of a C# program, and the nullable annotations of C# 8 exist to move it from run time to the compiler.

<Nullable>enable</Nullable> in the project file, which every project of this course has, turns on the analysis. From then on string means "a string, not null" and string? means "a string or null", and the compiler compares the two.

Two warnings, one build

This program has two nullable mistakes. A property of type string is left at its default value, which is null, and a local of type string is assigned null.

string name = null; Console.WriteLine($"[{name}]"); var person = new Person { Name = "Ada" }; Console.WriteLine($"[{person.Name}] [{person.Nickname ?? "none"}]"); class Person { public string Name { get; set; } public string? Nickname { get; set; } }

dotnet build
dotnet run

Program.cs(8,19): warning CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
Program.cs(1,15): warning CS8600: Converting null literal or possible null value to non-nullable type.

Build succeeded.

Program.cs(8,19): warning CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
Program.cs(1,15): warning CS8600: Converting null literal or possible null value to non-nullable type.
2 Warning(s)
0 Error(s)

Time Elapsed 00:00:05.64
[]
[Ada] [none]

The build prints each warning twice: once when the compiler reports it and once in the summary under the "Build succeeded" line, with the counts. That is the normal output of MSBuild, not a doubled message.

Both are warnings: the program was built and ran, and the two lines printed. CS8618 is about the constructor the class does not have (the compiler wrote a default one), and CS8600 is about the assignment on line 1. The position (8,19) points at the property name, and (1,15) at the null.

A warning of this kind is a promise the compiler could not verify, not a proof of a bug: the program above never dereferences name, so it does not crash. It is still a bug in waiting, which is why the lesson on warnings as errors turns it into a failure.

Flow analysis and the null checks

The compiler tracks what it knows about a variable at each line. A check narrows the type, and the narrowing holds until something could change it:

string? nickname = GetNickname(); if (nickname is not null) { Console.WriteLine(nickname.Length); } Console.WriteLine(nickname?.Length ?? 0); static string? GetNickname() => null;

dotnet build
dotnet run

Build succeeded.
0 Warning(s)
0 Error(s)

0

Neither line warns. Inside the if, the compiler knows nickname is not null, so .Length is allowed; outside it, ?. reads the length only when the value is there, and ?? supplies a 0 otherwise. The function returns null here, so the block is skipped and the program prints 0.

Three operators do most of this work, and the course meets them again and again: ?. for a member access that may be skipped, ?? for a default value, and ??= for an assignment when the value is null. The null-forgiving operator ! says "trust me, it is not null" and turns the warning off without a check; a page should use it only when it can say why.

The fixed version

The two warnings of the first program have two fixes. A property that must be set is required, and a value that may be absent is string?.

var person = new Person { Name = "Ada" }; Console.WriteLine($"{person.Name} ({person.Nickname?.Length.ToString() ?? "no nickname"})"); class Person { public required string Name { get; init; } public string? Nickname { get; init; } }

dotnet build
dotnet run

Build succeeded.
0 Warning(s)
0 Error(s)

Ada (no nickname)

No warning, because every construction of Person now has to name Name, which the compiler enforces with error CS9035: Required member 'Person.Name' must be set in the object initializer or attribute constructor. A required member is the modern answer to the CS8618 warning and replaces the constructor that only assigns fields.

Exercises

  1. Remove { Name = "Ada" } from the fixed program and read CS9035.
  2. Add public string City { get; set; } = ""; to the first class. Why does the new property print no warning?
  3. Replace nickname?.Length ?? 0 with nickname!.Length. Does the build warn? Does the program crash?
  4. Set <Nullable>disable</Nullable> and build the first program again. Which of the two warnings disappears, and what does that tell you about the setting?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the type string? mean in a project with Nullable enabled?

    Answer

    A string or null, and the compiler checks every use

    The question mark adds null to the set of values, and the flow analysis then requires a check before a member access.

  2. Which warning reports a non-nullable property that a constructor leaves null?

    Answer

    CS8618

    CS8618 names the property and suggests the required modifier or a nullable declaration; CS8600 is the assignment and CS8602 a dereference.

  3. What does this program print? string? name = null; Console.WriteLine(name?.Length ?? -1);

    Answer

    -1

    The ?. skips the member access on null and yields null, which ?? turns into -1.

  4. What does this program print? var p = new Person { Name = "Ada" }; Console.WriteLine(p.Name); class Person { public required string Name { get; init; } }

    Answer

    Ada

    The object initialiser satisfies the required member, so the program builds and prints the name.

  5. What happens to a program that dereferences a string? without a check?

    Answer

    The build warns with CS8602 and the program may throw NullReferenceException at run time

    Nullable warnings are warnings, so the program is built; the dereference of a real null then throws NullReferenceException.

  6. What does this program print? string? a = null; string b = a ?? "fallback"; Console.WriteLine(b);

    Answer

    fallback

    The ?? operator substitutes the right side when the left is null, so b holds the fallback and no warning is reported.

  7. Which operator says that a value is not null without a check?

    Answer

    The null-forgiving ! after the expression

    The postfix ! silences the analysis and promises a value; ?. and ?? avoid the dereference instead of promising anything.

  8. What does this program print? int? maybe = null; Console.WriteLine(maybe.HasValue); Console.WriteLine(maybe.GetValueOrDefault(7));

    Answer

    False / 7

    A nullable value type reports whether it holds a value, and GetValueOrDefault returns the argument when it does not.

  9. Why is CS8618 a warning rather than an error?

    Answer

    The compiler cannot prove the value stays null, and the program may be correct without the property

    The analysis reports what it cannot verify; a constructor, a required member or a nullable declaration resolves it, and warnings-as-errors turns it into a failure.

  10. What does this program print? string? text = "abc"; if (text is not null) { Console.WriteLine(text.ToUpper()); }

    Answer

    ABC

    The null check narrows the type inside the block, so the dereference is allowed and ToUpper returns ABC.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev