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

1

20

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(" ", "");
}
Creamcups answered 13/3, 2022 at 19:19 Comment(6)
Why do you want to "tell" something to the compiler?Joerg
I think you are already telling the compiler that by writing this code LOLDiscommodity
Put [return: NotNullIfNotNull("input")] before the mehtod.Irena
@RafaelplayerxdYT This is part of nullable references where you don't want the compiler to complain that something is null when you know it isn't and the compiler cannot figure that out without an attribute.Irena
@Discommodity No the compiler will not know that the method will return a non-nullable string unless you tell it with an attribute.Irena
@Irena thanks, never knew that this existed, long time without coding C#Joerg
U
40

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

Unlikelihood answered 13/3, 2022 at 19:29 Comment(4)
Thanks, was harder to find that article than anticipated!Creamcups
Starting with C# 11 you can use nameof in the attribute like so [return: NotNullIfNotNull(nameof(input))]Defelice
Note for people like me that wanted to apply this to async methods, it currently isn't supported to apply NotNullIfNotNull on async Task<T?> return types :( github.com/dotnet/csharplang/discussions/2793Misteach
so cool! My thought: no way such a thing exists, but let's google it anyway :) good i did...Spud

© 2022 - 2024 — McMap. All rights reserved.