Search code examples
c#exceptionnullable-reference-types

Extension method to validate nullity when nullable reference are enabled


I have the following method:

public static void NotNull<TException>([ValidatedNotNull] object? data, string? message = null) where TException : Exception, new()

Basically, I use it to ensure that data is not null. It works well, however, when I enable nullable reference, Visual Studio continues to underline in green the object I pass to this method because it considers that I didn't check whether it's null or not although I use the ValidatedNotNull attribute.

Is there a way to tell Visual Studio that I validated the nullity of the object using my custom method?

Thanks


Solution

  • Use NotNullAttribute (see the attributes for null-state static analysis interpreted by the C# compiler docs):

    A nullable parameter, field, property, or return value will never be null.

    static void NotNull<TException>([NotNull]object? data, string? message = null) where TException : Exception, new()
    {
       ...
    }