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).
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
?.
:2) Multiple enumeration with reassignment in conditional:
3) Multiple enumeration of
IQueryable
viaIEnumerable
: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 orvalues
is not null and is enumerated twice. 2) Ifvalues.Count() != 0
, thenvalues
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).