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

CA1851: fails to detect multiple enumeration in certain scenarios #7308

Open
hchamre opened this issue May 10, 2024 · 0 comments
Open

CA1851: fails to detect multiple enumeration in certain scenarios #7308

hchamre opened this issue May 10, 2024 · 0 comments

Comments

@hchamre
Copy link

hchamre commented May 10, 2024

Analyzer

Diagnostic ID: CA1851: Possible multiple enumerations of IEnumerable collection

Analyzer source

NuGet Package: Microsoft.CodeAnalysis.NetAnalyzers

Version: 8.0.0

Describe the bug

Several cases of multiple enumeration are not detected by the analyzer.

Steps To Reproduce

Preparation:

  • Create an empty C# project.

  • Enable NetAnalyzers.

  • Enable CA1851 in EditorConfig by setting severity to error or warning.

  • Use the following code snippets:

    1. Multiple enumeration with null-conditional ?.:

      IEnumerable<string>? values = SomeMethodReturning<IEnumerable<string>?>();
      int? x = values?.Count() + values?.Count();
    2. Multiple enumeration with reassignment in conditional:

      IEnumerable<int> values = SomeMethodReturning<IEnumerable<int>>();
      if (values.Count() == 0)
      {
          values = new List<int> { 123 };
      }
      int x = values.Count();
    3. Multiple enumeration of IQueryable via IEnumerable:

      IEnumerable<int> values = SomeMethodReturning<IQueryable<int>>();
      int x = values.Count() + values.Count();

Expected behavior

Each of the above snippets should generate a "multiple enumeration" diagnostic. Here is my reasoning:

  1. Either values is null and then it is never enumerated or values is not null and is enumerated twice.
  2. If values.Count() != 0, then values is enumerated twice.
  3. values is enumerated twice.

Actual behavior

None of the snippets generate diagnostics.

Additional context

Rider has a similar inspection which is able to flag 1) and 2), but not 3).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant