Sprog
Bemærk
Adgang til denne side kræver godkendelse. Du kan prøve at logge på eller ændre mapper.
Adgang til denne side kræver godkendelse. Du kan prøve at ændre mapper.
| 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 10 | As suggestion |
| Enabled by default in .NET 11 | As suggestion |
| Applicable 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.
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
It's safe to suppress a violation of this rule if you're not concerned about the performance impact of the search invocation in question.
If you're using Entity Framework Core (EF Core) or other LINQ providers, you should suppress this rule for scenarios where you query a database using string.Contains(string) in an expression tree. Some LINQ providers cannot translate String.Contains(Char) to SQL, throwing an InvalidOperationException at run time. For more information, see Translation of built-in .NET string operations.
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.