visual studio – Indicate C# Compiler not to show warnings for extension methods


(As Jeremy Lakeman commented…)

You can add the NotNullWhen(true) attribute to the input parameter to specify that when HasContent returns true, it means that the argument passed as the input parameter will not be null (even though the string? type allows it to be null).

Then the wavy goes away because the compiler knows it’s not null based on it being in the true block of the if conditional.

    public static class StringExtensions {
        public static bool HasContent([NotNullWhen(true)] this string? input) {
            return !string.IsNullOrWhiteSpace(input);
        }

        public static void TestMethod(string? test) {
            if (test.HasContent()) {
                var str = test.ToUpper();
            }
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *