Async method's return decorated with "NotNullIfNotNull" still returns variable that may be null

150 Views Asked by At

According to this documentation I can decorate a method with NotNullIfNotNull attribute. However the following code does not work:

using System.Diagnostics.CodeAnalysis;

var a = await Test("abc");
Console.WriteLine(a.Length);

[return: NotNullIfNotNull(nameof(input))]
static async Task<string?> Test(string? input)
{
    return await Task.FromResult(input);
}

I still receives a warning at a.Length (Dereference of a possibly null reference):

enter image description here

I suspect Task is causing this issue. I can confirm the issue only happen to async (returning Task) methods. How should I fix this problem?

0

There are 0 best solutions below