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:
using System.Text.RegularExpressions;
class Example
{
public int CountWords(string text)
{
// Violation
return Regex.Matches(text, @"\b\w+\b").Count;
}
}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 ClassThe following code snippet fixes the violation:
using System.Text.RegularExpressions;
class Example
{
public int CountWords(string text)
{
// Fixed
return Regex.Count(text, @"\b\w+\b");
}
}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 ClassWhen 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.
#pragma warning disable CA1875
// The code that's violating the rule is on this line.
#pragma warning restore CA1875To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1875.severity = noneFor more information, see How to suppress code analysis warnings.