Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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 |
String.Contains(string)
is used when String.Contains(char)
is available.
When searching for a single character, String.Contains(char)
offers better performance than String.Contains(string)
.
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
Suppress a violation of this rule if you're not concerned about the performance impact of the search invocation in question.
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.
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
Mar 17, 9 PM - Mar 21, 10 AM
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register now