Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(" ", "");
}
like image 360
Michal Ciechan Avatar asked Sep 13 '25 16:09

Michal Ciechan


1 Answers

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

like image 64
Svyatoslav Danyliv Avatar answered Sep 15 '25 06:09

Svyatoslav Danyliv