Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading