Specify StringComparison for clarity
Specify StringComparison for clarity
Microsoft docsDescription
Many string compare operations provide an overload that accepts a System.StringComparison enumeration value as a parameter.
Whenever an overload exists that takes a System.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 Specify string comparisons explicitly. This rule does not consider the default System.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.
Cause
A string comparison operation uses a method overload that does not set a System.StringComparison parameter.
How to fix violations
To fix a violation of this rule, change string comparison methods to overloads that accept the System.StringComparison enumeration as a parameter. For example, change str1.IndexOf(ch1) to str1.IndexOf(ch1, StringComparison.Ordinal).
Example
#pragma warning disable CA1307
// The code that's violating the rule is on this line.
#pragma warning restore CA1307When to suppress
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.