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

Code analysis

CA1875: Use 'Regex.Count'

Learn about code analysis rule CA1875: Use 'Regex.Count'

CA1875 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.Text.RegularExpressions.MatchCollection.Count property of the MatchCollection from System.Text.RegularExpressions.Regex.Matches is used to get the count of matches.

Rule description

System.Text.RegularExpressions.Regex.Count is simpler and faster than Regex.Matches(...).Count. The Count() method is optimized for counting matches without materializing the full System.Text.RegularExpressions.MatchCollection. Calling Matches() and then accessing .Count does unnecessary work that can impact performance.

How to fix violations

Replace calls to Regex.Matches(...).Count with Regex.Count(...).

A code fix that automatically performs this transformation is available.

Example

The following code snippet shows a violation of CA1875:

csharp
using System.Text.RegularExpressions;

class Example
{
    public int CountWords(string text)
    {
        // Violation
        return Regex.Matches(text, @"\b\w+\b").Count;
    }
}
vb
Imports System.Text.RegularExpressions

Class Example
    Public Function CountWords(text As String) As Integer
        ' Violation
        Return Regex.Matches(text, "\b\w+\b").Count
    End Function
End Class

The following code snippet fixes the violation:

csharp
using System.Text.RegularExpressions;

class Example
{
    public int CountWords(string text)
    {
        // Fixed
        return Regex.Count(text, @"\b\w+\b");
    }
}
vb
Imports System.Text.RegularExpressions

Class Example
    Public Function CountWords(text As String) As Integer
        ' Fixed
        Return Regex.Count(text, "\b\w+\b")
    End Function
End Class

When to suppress warnings

It's safe to suppress a warning from this rule if performance isn't a concern or if you're targeting a version of .NET that doesn't include Regex.Count (prior to .NET 7).

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 CA1875
// The code that's violating the rule is on this line.
#pragma warning restore CA1875

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

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

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

See also