Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positive 'possible null reference argument' after ensuring non-null via the null coalescing operator #73426

Closed
Treit opened this issue May 10, 2024 · 1 comment
Labels
Area-Compilers untriaged Issues and PRs which have not yet been triaged by a lead

Comments

@Treit
Copy link

Treit commented May 10, 2024

Repro

The following program results in a warning about passing a possible null argument to DoSomething. As far as I can see there is no possibility the argument could be null.

using System;
using System.Collections.Generic;

var ids = GetIds();

if ((ids?.Count ?? 0) == 0)
{
    return;
}

DoSomething(ids);

static void DoSomething(List<string> ids)
{
    Console.WriteLine(ids.Count);
}

static List<string>? GetIds()
{
    return null;
}

Replacing if ((ids?.Count ?? 0) == 0) with if (ids is null || ids.Count == 0) (or various other pattern matching techniques to accomplish the same thing) makes the warning go away, even though Sharplab says they lower to the same code.

We have this pattern in many places in a large codebase and it makes turning on nullable checks difficult. It would be much nicer if the compiler could detect that the variable cannot be null in this case.

@dotnet-issue-labeler dotnet-issue-labeler bot added Area-Compilers untriaged Issues and PRs which have not yet been triaged by a lead labels May 10, 2024
@CyrusNajmabadi
Copy link
Member

CyrusNajmabadi commented May 10, 2024

Closing out. The compiler doesn't track the null relationship through arithmetic expressions (like (ids?.Count ?? 0) and then teh ==0).

You can write this as:

if (ids is null || ids.Count == 0)
{
    return;
}

or

if (ids is not { Count: > 0 })
    return;

It would be much nicer if the compiler could detect that the variable cannot be null in this case.

We've looked at this sort of relationship before and decided the large increase in analysis complexity is not worth it, given hte simple and idiomatic transforms available.

@CyrusNajmabadi CyrusNajmabadi closed this as not planned Won't fix, can't repro, duplicate, stale May 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area-Compilers untriaged Issues and PRs which have not yet been triaged by a lead
Projects
None yet
Development

No branches or pull requests

2 participants