DEV Community

Steve Bjorg for LambdaSharp

Posted on • Updated on

C# - Asserting a value is not null in null-aware code

C# 8.0 introduced the long desired ability to annotate reference types as potentially having a null value. There is a lot to digest when making code null-aware. Some of it is straightforward, other times, not so much.

One attribute, I found puzzling was the [NotNull], which is described as applying to return values. However, it also has a great use for parameters. Specifically, for null assertion methods.

Consider the following definition of AssertIsNotNull().

void AssertIsNotNull([NotNull] object? nullableReference) {
    if(nullableReference == null) {
        throw new ArgumentNullException();
Enter fullscreen mode Exit fullscreen mode

With this annotated version, we can now write the following code and get no compiler warnings on potential null access. (NOTE: this code is just for illustration purposes)

int MyMethod(string? text) {
    return text.Length;
Enter fullscreen mode Exit fullscreen mode

Effectively, the [NotNull] attribute tells the compiler that the text value is not null once it has passed the AssertIsNotNull() invocation. Since the method throws an exception otherwise, this is a safe statement to make about the text parameter.

The motivation for AssertIsNotNull() is to avoid using the null forgiving operator (!), which can be hard to track down when used as a suffix.

I've found this pattern quite useful and wish it had been included as an example, but at least, it's easy enough to share here with fellow coders.

Happy hacking!

Top comments (2)

mburszley profile image
Maximilian Burszley

The whole point of nullable references is being explicit and you're writing APIs as if the feature isn't enabled.

bjorg profile image
Steve Bjorg • Edited

Thanks for highlighting the fact that I didn't make the motivation clear for this. I'm not a fan of the null forgiving operator (!), because it's hard to track down. Using AssertIsNotNull() achieves the same outcome and it's easier to find.