Home > Net >  Why does intellicode '... is not null' when it is cleary null?
Why does intellicode '... is not null' when it is cleary null?

Time:04-06

Edit: Thanks to canton7 I will be looking into enter image description here

Called method:

public async Task<List<Product>> GetProductListAsync()
{
    return null;
}

Image:

enter image description here

CodePudding user response:

You have the C# 8 feature "Nullable Reference Types" (NRTs) enabled. This adds a layer of static analysis, which tells you when a reference type might be null, and warn you if you dereference something which might be null. See this doc and this MSDN blog post.

You can disable NRTs by setting <Nullable>disable</Nullable> in your .csproj.

The signature Task<List<Product>> GetProductListAsync() promises that this method will return a non-null Task, containing a non-null List of non-null Products.

Any code which calls this method only sees the signature. The compiler trusts that you wrote the signature correctly. Since the signature says that this method does not return null, this means that _products is shown as "not null".

(Think about what would happen if this method was defined in a different DLL. The compiler doesn't have the source code available to go analysing it. This sort of whole-program type inference is also very costly and fragile: it's much better to have interfaces explicitly stated by the programmer, rather than inferred.)

However, you have broken this promise in the implementation of the method, where you do return null. This is where the compiler moans at you. The CS8603 in your final screenshot shows the compiler complaining because the method signature promises that you won't return null, and yet you have return null.

If the method really can return null, then its signature should be:

Task<List<Product>?> GetProductListAsync()

This will make the warning on the return null go away, and _products will be shown as "maybe null".

  • Related