In C# indicate to static analyzers that a method guarantees non-null values

414 Views Asked by At

With .NET 6, it is easy to create helper or extension methods that can throw an exception without dirtying up the stack trace. For example:

    [System.Diagnostics.StackTraceHidden]
    public static void ThrowIfNullOrWhitespace(this string? stringValue, Exception exception)
    {
        if (string.IsNullOrWhiteSpace(stringValue))
            throw exception;
    }

In this case, you can call that method

foo.ThrowIfNullOrWhitespace(new ArgumentException("null or whitespace"));

but subsequent uses of foo in the code still get "possible null value" squiggles in the editor.

I also see this issue in more mundane cases where methods like foo = DoSomething(foo) guarantee a non-null result internally.

Is there an attribute or some other way to tell the C# static code analyzers that these kinds of methods enforce postconditions that guarantee that foo is not null?

1

There are 1 best solutions below

0
Blindy On BEST ANSWER

The attribute you're looking for is [NotNull], used like this:

public static void ThrowIfNullOrWhitespace([NotNull]this string? stringValue, Exception exception)

You can see literally the same example in the official documentation here.

And you can see your function implemented in the Windows Community Toolkit here.