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

Code analysis

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

Use String.Contains(char) instead of String.Contains(string) when searching for a single character

CA1847 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

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.

csharp
public bool ContainsLetterI()
{
    var testString = "I am a test string.";
    return testString.Contains("I");
}
vb
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.

csharp
public bool ContainsLetterI()
{
    var testString = "I am a test string.";
    return testString.Contains('I');
}
vb
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.

csharp
#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.

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

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

See also