Nullability provides developers with development-time warnings that can help reduce dereferencing issues. These errors can be costly, but with the power of a few additional checks in code, developers can easily avoid them, putting them in control of their code’s quality.

In this post, we’ll see a code sample that should be “safe” yet continues to give IDE and build-time warnings about dereferencing of a possibly null reference. We’ll also see how to adjust your code to remove unnecessary warnings in current and future projects.

Dereference of a possibly null reference

Let’s look at some basic C# code, which you likely have something similar to in your projects.

var database = new Database();

// Name cannot be null when Initialize is true
if (database.Initialized)
{
    // This has a warning about Name being null
    var length = database.Name.Length;
    
    Console.WriteLine($"{database.Name} and length is {length}");
}

Console.WriteLine("Hello, World!");

public class Database
{
    public string? Name { get; set; }
    public bool Initialized => Name is not null;
}

Here, we have a Database class, and we know the Name property will never be null if the boolean property of Initialized returns true. Yet, you likely see a yellow line warning you with the message “Dereference of a possibly null reference” in your editor. Additionally, this warning shows up in your build logs.

Program.cs(9,18): Warning CS8602 : Dereference of a possibly null reference.

We can ignore this, right? Well, not if your team uses the MSBuild element of TreatWarningsAsErrors.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net9.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    </PropertyGroup>

</Project>

Oh no! Our build is broken!

0>Program.cs(9,18): Error CS8602 : Dereference of a possibly null reference.
0>------- Finished building project: ConsoleApp2. Succeeded: False. Errors: 1. Warnings: 0

How do we fix this?

Using MemberNotNullWhen On Boolean Properties

There are several attributes under the System.Diagnostics.CodeAnalysis namespace that we can use to give the compiler hints about the safety of the written code. The attribute we’ll use is MemberNotNullWhen, which allows us to decorate a property or method that returns a bool result and tie the safety check to one or more other properties.

using System.Diagnostics.CodeAnalysis;

var database = new Database();

// Name cannot be null when Initialize is true
if (database.Initialized)
{
    // The warning/error is now gone
    var length = database.Name.Length;
    
    Console.WriteLine($"{database.Name} and length is {length}");
}

Console.WriteLine("Hello, World!");

public class Database
{
    public string? Name { get; set; }
    // this attribute fixes the issue
    [MemberNotNullWhen(true, nameof(Name))]
    public bool Initialized => Name is not null;
}

The steps in the code are as follows:

  1. Decorate a boolean property or method that returns bool with MemberNotNullWhen.
  2. Choose the value state that signals safety to the compiler.
  3. Choose one or more nullable members covered by the bool member.

There should be no editor warnings or build errors, and you can live the good life. I hope you found this post helpful. As always, thank you for reading. Cheers.