nunit.analyzers icon indicating copy to clipboard operation
nunit.analyzers copied to clipboard

Improper use of Count Linq method should be detected when Length property should be used.

Open manfred-brands opened this issue 1 year ago • 0 comments

The below occurred when changing a variable from a List to an ImmutableArray. The same error occurs on a normal array (string[]) The Count previously was a property on the List.

[Test]
public void ShouldNotAllowCountLinqMethodOnArray()
{
    ImmutableArray<string> names = GetNames();

    Assert.That(names.Count, Is.EqualTo(1));

    static ImmutableArray<string> GetNames() => ImmutableArray.Create("NUnit");
}

ImmutableArray doesn't have a Count property but a Length one. The above code actually calls the Count() Linq method.

When using Assert.That(names.Count(), Is.EqualTo(1)); roslyn raises CA1829 to use the Length property. Roslyn doesn't know that the above example will evaluate the method ActualValueDelegate.

manfred-brands avatar May 01 '23 06:05 manfred-brands