C#idiomatic C#
ca1829fundamentals/code-analysis/quality-rules

Code analysis

CA1829: Use Length/Count property instead of Enumerable.Count method

Learn about code analysis rule CA1829: Use Length/Count property instead of Enumerable.Count method

CA1829 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

The System.Linq.Enumerable.Count LINQ method was used on a type that supports an equivalent, more efficient Length or Count property.

Rule description

This rule flags the System.Linq.Enumerable.Count LINQ method calls on collections of types that have equivalent, but more efficient Length or Count property to fetch the same data. Length or Count property does not enumerate the collection, hence is more efficient.

This rule flags System.Linq.Enumerable.Count calls on the following collection types with Length property:

This rule flags System.Linq.Enumerable.Count calls on the following collection types with the Count property:

The analyzed collection types may be extended in the future to cover more cases.

How to fix violations

To fix a violation, replace the System.Linq.Enumerable.Count method call with use of the Length or Count property access. For example, the following two code snippets show a violation of the rule and how to fix it:

csharp
using System.Collections.Generic;
using System.Linq;

class C
{
    public int GetCount(int[] array)
        => array.Count();

    public int GetCount(ICollection<int> collection)
        => collection.Count();
}
csharp
using System.Collections.Generic;

class C
{
    public int GetCount(int[] array)
        => array.Length;

    public int GetCount(ICollection<int> collection)
        => collection.Count;
}

When to suppress warnings

It's safe to suppress a violation of this rule if you're not concerned about the performance impact from unnecessary collection enumeration to compute the count.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA1829
// The code that's violating the rule is on this line.
#pragma warning restore CA1829

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA1829.severity = none

For more information, see How to suppress code analysis warnings.

See also