Rediger

Del via


CA1847: Use String.Contains(char) instead of String.Contains(string) with single characters

Property Value
Rule ID CA1847
Title Use String.Contains(char) instead of String.Contains(string) with single characters
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As suggestion

Cause

String.Contains(string) is used when String.Contains(char) is available.

Rule description

When searching for a single character, String.Contains(char) offers better performance than String.Contains(string).

How to fix violations

In general, the rule is fixed simply by using a char literal instead of a string literal.

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

This code can be changed to use a char literal instead.

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

When to suppress warnings

Suppress a violation of this rule if you're not concerned about the performance impact of the search invocation in question.

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

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

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

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

See also