Home > Software engineering >  C# Nullable Annotation that method returns not null if parameter is not null
C# Nullable Annotation that method returns not null if parameter is not null

Time:03-14

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(" ", "");
}

CodePudding user response:

Use the following attribute:

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

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

  • Related