Cause
The System.Text.RegularExpressions.Group.Success property of the result from System.Text.RegularExpressions.Regex.Match is used to check if a pattern matches.
Rule description
System.Text.RegularExpressions.Regex.IsMatch is simpler and faster than Regex.Match(...).Success. The IsMatch method is optimized for the case where you only need to know whether a match exists, rather than what the match is. Calling Match() and then checking System.Text.RegularExpressions.Group.Success does unnecessary work that can impact performance.
How to fix violations
Replace calls to Regex.Match(...).Success with Regex.IsMatch(...).
A code fix that automatically performs this transformation is available.
Example
The following code snippet shows a violation of CA1874:
using System.Text.RegularExpressions;
class Example
{
public bool IsValidEmail(string email)
{
// Violation
return Regex.Match(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$").Success;
}
}Imports System.Text.RegularExpressions
Class Example
Public Function IsValidEmail(email As String) As Boolean
' Violation
Return Regex.Match(email, "^[^@\s]+@[^@\s]+\.[^@\s]+$").Success
End Function
End ClassThe following code snippet fixes the violation:
using System.Text.RegularExpressions;
class Example
{
public bool IsValidEmail(string email)
{
// Fixed
return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
}
}Imports System.Text.RegularExpressions
Class Example
Public Function IsValidEmail(email As String) As Boolean
' Fixed
Return Regex.IsMatch(email, "^[^@\s]+@[^@\s]+\.[^@\s]+$")
End Function
End ClassWhen to suppress warnings
It's safe to suppress a warning from this rule if performance isn't a concern.
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 CA1874
// The code that's violating the rule is on this line.
#pragma warning restore CA1874To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1874.severity = noneFor more information, see How to suppress code analysis warnings.