C# – Suppress nullable warnings (CS8602)

Sometimes the compiler shows unhelpful nullable warnings. Here’s an example of it showing warning CS8602, when it’s obvious to any human reading the code that you’re doing a null-check already (in ThrowIfNull()):

void Process(Employee? employee)
{
    ThrowIfNull(employee);

    employee.DoWork(); //Nullable warning CS8602
    employee.GetReport();
}
Code language: C# (cs)

Besides disabling the Nullable feature, there are two ways to suppress nullable warnings on a case-by-case basis:

  1. Use the [NotNull] attribute on the method parameter.
  2. Use the null-forgiving operator.

I’ll show both options below.

Option 1 – Use the [NotNull] attribute

In your null-checking method, use the [NotNull] attribute on the parameter you’re null-checking (and make it a nullable reference with the ? operator):

using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

void ThrowIfNull([NotNull] object? arg,
            [CallerArgumentExpression("arg")] string? argName = null)
{
    if (arg == null)
    {
        throw new ArgumentNullException(argName);
    }
}
Code language: C# (cs)

Note: Consider using the built-in ArgumentNullException.ThrowIfNull() method (added in .NET 6). It does the same thing as above. On the other hand, the main reason I’d suggest using your own version is so you can hide it from the stack trace.

In practical terms, this tells the compiler that the reference is being null-checked here, so don’t show Nullable warnings about it in the calling code.

This is a very effective option if you’re calling this method all over the place (which you probably are). It solves the problem at the root with minimal effort on your part.

Option 2 – Use the null-forgiving operator !

You can use the null-forgiving operator ! to get rid of Nullable warnings on a case-by-case basis:

void Process(Employee? employee)
{
    ThrowIfNull(employee);

    employee!.DoWork(); //This was showing 
    employee.GetReport();
}

Code language: C# (cs)

This basically tells the compiler that you know it’s not null, so don’t bother analyzing it. This is a good option if you can’t change the null-checking method.

Leave a Comment