4

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?

6
  • 4
    It's marking Task<T>, not T. Commented Aug 7, 2023 at 16:55
  • @madreflection yes I noticed that. How should I decorate it instead? Commented Aug 7, 2023 at 19:03
  • The attribute doesn't provide a way to decorate the type parameters. Feature request. Commented Aug 7, 2023 at 19:04
  • 1
    ...is not null, it needs to express those separately. It's quite involved. I'm sure the compiler team would like to do it, but they have to examine the use cases and make sure they don't design themselves into a corner. Incremental steps help avoid that. Commented Aug 7, 2023 at 19:11
  • 2
    @madreflection you are right. I found the discussion about it. Been 4 years and there seem to be no solution anytime soon Commented Aug 7, 2023 at 19:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.