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

Code analysis

CA1858: Use StartsWith instead of IndexOf

Learn about code analyzer rule CA1858 - Use StartsWith instead of IndexOf

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

Cause

System.String.IndexOf is called and its result is compared against zero.

Rule description

It's more efficient and clearer to call System.String.StartsWith than to call System.String.IndexOf and compare the result with zero to determine whether a string starts with a given prefix.

IndexOf searches the entire string, while StartsWith only compares at the beginning of the string.

How to fix violations

Replace the call to System.String.IndexOf with a call to System.String.StartsWith.

Example

The following code snippet shows a violation of CA1858:

csharp
bool M(string s)
{
    return s.IndexOf("abc") == 0;
}
vb
Function M(s As String) As Boolean
    Return s.IndexOf("abc") = 0
End Function

The following code snippet fixes the violation:

csharp
bool M(string s)
{
    return s.StartsWith("abc");
}
vb
Function M(s As String) As Boolean
    Return s.StartsWith("abc")
End Function

When to suppress warnings

It's safe to suppress this warning if performance isn't a concern.

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

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

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

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