Edit

Share via


CA1865-CA1867: Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char

Property Value
Rule ID CA1865-CA1867
Title Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 CA1865—As suggestion
CA1866—As suggestion
CA1867—No

Cause

string.Method(string) is used when string.Method(char) was available.

The target methods on string for these rules:

  • StartsWith
  • EndsWith
  • IndexOf
  • LastIndexOf

The following table summarizes the conditions for each of the related rule IDs.

Diagnostic ID Description Code fix available
CA1865 Applies when a safe transformation can be performed automatically with a code fix. Yes
CA1866 Applies when there's no specified comparison. No
CA1867 Applies for any other string comparison not covered by the other two rules. No

CA1867 is disabled by default.

Rule description

The overload that takes a char parameter performs better than the overload that takes a string parameter.

How to fix violations

To fix a violation, use the char parameter overload instead of the string parameter overload.

Consider the following example:

public bool StartsWithLetterI()
{
    var testString = "I am a test string.";
    return testString.StartsWith("I");
}
Public Function StartsWithLetterI() As Boolean
    Dim testString As String = "I am a test string."
    Return testString.StartsWith("I")
End Function

This code can be changed to pass 'I' to StartsWith instead of the string "I".

public bool StartsWithLetterI()
{
    var testString = "I am a test string.";
    return testString.StartsWith('I');
}
Public Function StartsWithLetterI() As Boolean
    Dim testString As String = "I am a test string."
    Return testString.StartsWith("I"c)
End Function

When to suppress warnings

Suppress a violation of this rule if you're not concerned about the performance impact of calling the method with a string.

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

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

[*.{cs,vb}]
dotnet_diagnostic.CA1865.severity = none
dotnet_diagnostic.CA1866.severity = none
dotnet_diagnostic.CA1867.severity = none

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

See also