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

Code analysis

CA1307: Specify StringComparison for clarity

Learn about code analysis rule CA1307: Specify StringComparison for clarity

CA1307 Globalization enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

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

Rule description

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.

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).

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.

csharp
#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.

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

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

See also