C# – Get rid of Nullable warnings when you’re checking for null in another method

When you’re calling a helper method that does null checking (throw-if-null), you’ll still get Nullable warnings in the calling code because the compiler doesn’t know you’re already doing null checking.

Here’s an example:

void Process(Employee? employee) { ThrowIfNull(employee); employee.DoWork(); //Nullable warning CS8602 employee.GetReport(); }
Code language: C# (cs)

ThrowIfNull() throws an exception if employee is null, so you know for sure that it won’t be null in the rest of the method. It can’t be null, and yet the compiler warns about it possibly being null (warning CS8602 in this example).

To get rid of the warnings, you have to tell the compiler you know it’s not null. There are two ways to do that: 1) Use [NotNull] in the null-checking method or 2) Use the null-forgiving operator ! in the calling code. I’ll show both options below.

Option 1 – Use [NotNull] in the null-checking method

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 ! in the calling code

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(); 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