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?
The attribute you're looking for is
[NotNull], used like this: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.