Reputation: 13898
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(" ", "");
}
Upvotes: 22
Views: 6071
Reputation: 27426
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
Upvotes: 44