Search code examples
c#.netnullablenullable-reference-types

C# Nullable Annotation that method returns not null if parameter is not null


How can I tell compiler that the following extension method returns not null if input is not null?

public static string? SomeMethod(this string? input)
{
    if (string.IsNullOrEmpty(input))
        return input;

    // Do some work on non-empty input
    return input.Replace(" ", "");
}

Solution

  • Use the following attribute:

    [return: NotNullIfNotNull(nameof(input))]
    public static string? SomeMethod(this string? input)
    {
       ...
    }
    

    For further reading: Attributes for null-state static analysis interpreted by the C# compiler