skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Fix CS8602 and Nullability Warnings for Guarded Members

Fix CS8602 (dereference of a possibly null reference) in C# for guarded members using MemberNotNullWhen, without disabling nullability warnings.

6 min read Updated

If you’re staring at CS8602, “Dereference of a possibly null reference,” on a property you’ve already null-checked, the fix is the MemberNotNullWhen attribute, not a null-forgiving operator. 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 a possibly null reference. We’ll also see how to adjust your code to remove unnecessary warnings in current and future projects.

What is CS8602 and how do I fix it?

CS8602 is the C# compiler warning “Dereference of a possibly null reference.” It means you used . on a value the compiler’s flow analysis thinks could be null. Fix it by proving the value is not null before you use it: check it with is not null, access it with ?., or, when a property guards another property, tell the compiler with [MemberNotNullWhen]. Updated: November 2026.

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 Initialized returns true. Yet, you likely see a yellow line warning you with the message “Dereference of a possibly null reference” in your editor. This is the warning CS8602: Dereference of a possibly null reference message. This warning also 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.

For the basics of ?, ??, and ?., see the null handling section of my C# cheat sheet.

What other things trigger CS8602?

MemberNotNullWhen only covers the guarded-member case. Most CS8602 warnings come from simpler code.

string? name = Environment.GetEnvironmentVariable("APP_NAME");
var a = name.Length; // CS8602: name may be null
if (name is not null)
{
var b = name.Length; // fine: compiler knows it's not null
}
var c = name?.Length ?? 0; // fine: ?. short-circuits on null
var d = Find(1).Length; // CS8602: the return type is string?
string? Find(int id) => id > 1 ? "found" : null;
  • A null check the compiler can’t carry. Flow analysis tracks a local variable well. It does not track a check hidden behind a method or a separate property, which is the MemberNotNullWhen case above. For locals, is not null is the clearest check.
  • ?. as a safe dereference. name?.Length returns null instead of throwing. Pair it with ?? to supply a default.
  • The ! operator. name!.Length silences the warning, but you’ve only told the compiler to stop looking. If name is null at runtime, you still get a NullReferenceException. Use ! only when you can point to why the value is non-null and the compiler can’t see it. Otherwise it’s a lie that moves the failure to production. I make the same case in my post on C# nullable reference types, coming soon.
  • Libraries and deserializers. Nullability is a compile-time check. A library compiled without annotations, or a JSON deserializer filling a string property, can hand you null with no warning at all. Treat data from outside your code as nullable and validate it at the boundary.

CS8602 FAQ

What does CS8602 mean?

The compiler found a place where you read a member (.Length, .Name, a method call) on an expression whose null state is “maybe null.” It’s a hint that a NullReferenceException is possible, not proof that one will happen.

How do I suppress CS8602?

Prefer fixing it. Add a real null check, use ?., or annotate the guard with [MemberNotNullWhen]. If you must suppress it, you have two last-resort options:

// Per expression: the null-forgiving operator
var length = name!.Length;
// Per region: a pragma
#pragma warning disable CS8602
var other = name.Length;
#pragma warning restore CS8602

Both hide the warning and leave the bug. Scope a pragma tightly and always restore it.

Is CS8602 an error or a warning?

A warning by default. It becomes a build error when you set TreatWarningsAsErrors to true, or when you promote only this one with <WarningsAsErrors>CS8602</WarningsAsErrors>. Nullable analysis only runs when <Nullable>enable</Nullable> is set.

What’s the difference between CS8602, CS8600, and CS8604?

All three come from the same analysis and differ by where the maybe-null value lands:

  • CS8602: you dereference it (value.Length).
  • CS8600: you convert it to a non-nullable type (string t = maybeNull;).
  • CS8604: you pass it as an argument to a non-nullable parameter (Show(maybeNull)).

The same fixes apply to all three: prove it’s not null, or make the target nullable.

Fix the cause rather than silence the symptom, and CS8602 stops being noise and starts being the free null-safety check it was meant to be. No more editor squiggles, no broken builds, and far fewer NullReferenceExceptions in production. I hope you found this post helpful. As always, thank you for reading. Cheers.

Comments

Related Posts