Search code examples
c#.net-6.0visual-studio-2022pragma

Can my custom method satisfy Pragma Warnings?


For instance, when I do string.IsNullOrWhiteSpace(""), this satisfies the pragma warning:

CS8604: Possible null reference argument

Now, if I had defined an extension method called "".IsNull(), would it be possible to somehow get the IDE/Compiler to recognizer it as a valid handler for CS8604?

public static bool IsNull(this string? s) => string.IsNullOrWhiteSpace(s);

Solution

  • Yes - you want one of the attributes used by null-state static analysis.

    In this particular case, I think you want NotNullWhen:

    public static bool IsNull([NotNullWhen(false)] this string? s) => 
        string.IsNullOrWhiteSpace(s);