CA1307: Specify StringComparison for clarity

Property Value
Rule ID CA1307
Title Specify StringComparison for clarity
Category Globalization
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

A string comparison operation uses a method overload that does not set a StringComparison parameter.

Rule description

Many string compare operations provide an overload that accepts a StringComparison enumeration value as a parameter.

Whenever an overload exists that takes a StringComparison parameter, it should be used instead of an overload that does not take this parameter. By explicitly setting this parameter, your code is often made clearer and easier to maintain. For more information, see Specifying string comparisons explicitly.

Note

This rule does not consider the default StringComparison value used by the comparison method. Hence, it can be potentially noisy for methods that use the Ordinal string comparison by default and the user intended to use this default compare mode. If you only want to see violations only for known string methods that use culture-specific string comparison by default, please use CA1310: Specify StringComparison for correctness instead.

How to fix violations

To fix a violation of this rule, change string comparison methods to overloads that accept the StringComparison enumeration as a parameter. For example, change str1.IndexOf(ch1) to str1.IndexOf(ch1, StringComparison.Ordinal).

When to suppress warnings

It is safe to suppress a warning from this rule when clarity of intent is not required. For example, test code or non-localizable code may not require it.

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

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

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

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

See also