skip to content

As the lead setting C# conventions, what default would you choose for string comparison, and would you make CA1307, CA1309, CA1310 and CA1311 build errors?

level: principalimportance: should knowfreq 30%

answer

  1. identifiers versus displayed text
  2. none of the four is on by default
  3. correctness rule versus clarity rule
  4. noise decides adoption
  5. analyzers miss sorting

basics

~20 s

A sound default is ordinal comparison for everything except text shown to people, with every call naming its StringComparison. CA1310 and CA1311 are cheap, high-signal build errors; CA1307 and CA1309 add noise and suit only codebases wanting every comparison explicit.

solid answer

~50 s

I would make the rule "identifiers are ordinal, language is cultural, and every call says which": `Ordinal` or `OrdinalIgnoreCase` for keys, paths, tokens and user names; `CurrentCulture` (better, the user's own `CultureInfo`) only where text is displayed or searched by people; `InvariantCulture` only for persisted linguistic data. None of CA1307, CA1309, CA1310 or CA1311 is enabled by default in .NET 10. CA1310 flags only overloads that silently default to the culture, such as `StartsWith(string)` and `string.Compare(a, b)`, and CA1311 flags parameterless `ToUpper()` and `ToLower()`, so both catch real bugs with little noise and can be errors. CA1307 also flags calls that already default to ordinal, like `Contains(string)` and `Equals(string)`, and CA1309 flags every `string.Compare` or `Equals` call that does not pass `Ordinal` or `OrdinalIgnoreCase`, a deliberate `CurrentCulture` included. Those two buy uniformity with churn, so I would enable them per project, warnings first. No rule flags `Sort()` or `OrderBy` without a comparer, so review still matters.

code

plaintext · 1 line
plaintext
app.cs(2,19): error CA1310: The behavior of 'string.StartsWith(string)' could vary based on the current user's locale settings. Replace this call in '<top-level-statements-entry-point>' with a call to 'string.StartsWith(string, System.StringComparison)'.

go deeper

for a junior

Know that analyzers can flag string calls without a StringComparison, and that the safe default for identifiers is ordinal.

for a middle

Explain what each of CA1307, CA1309, CA1310 and CA1311 flags, and that none is enabled by default in .NET 10.

for a senior

Use the rules to clean a real codebase: start with CA1310 and CA1311, suppress justified culture-aware calls, and review sorting the analyzers miss.

for a principal

Own the trade-off between explicitness and churn: which rules become errors, where CA1309 applies, and whether a service should run in invariant globalization mode.

## The decision A team writing C# has to decide two things about string comparison: **what the default should be**, and **how hard the build should enforce it**. There is no single right answer, but the trade-offs are concrete. The default most teams converge on, and the one the .NET string guidance recommends, is: - **Identifiers are ordinal.** Keys, user names, role names, email domains, file paths, extensions, HTTP and XML tokens: `StringComparison.Ordinal` or `OrdinalIgnoreCase`, and `StringComparer.Ordinal` or `OrdinalIgnoreCase` for collections. - **Language is cultural.** Text a person reads or types, such as sorted lists, search boxes and report columns: `CurrentCulture` or `CurrentCultureIgnoreCase`, or better a `CultureInfo` for the specific user, because a server's current culture is not the reader's. - **Invariant is the exception.** `InvariantCulture` only for persisted data that is linguistic but must sort the same everywhere. - **Every call names its comparison**, even when the default already matches, because `String` mixes ordinal and culture-aware defaults and reviewers should not have to remember which is which. ## The four analyzer rules All four live in the Globalization category of the .NET code-quality analyzers, and all four are marked "Enabled by default in .NET 10: No". | Rule | Title | What it flags | Noise | |---|---|---|---| | CA1310 | Specify StringComparison for correctness | overloads whose default is culture-specific: `StartsWith(string)`, `EndsWith(string)`, `IndexOf(string)`, `string.Compare(a, b)`, `CompareTo` | low: every hit is a culture-dependent call | | CA1311 | Specify a culture or use an invariant version | `ToUpper()` and `ToLower()` without a culture | low | | CA1307 | Specify StringComparison for clarity | any call that has a `StringComparison` overload, including ordinal-default ones such as `Contains(string)`, `Equals(string)`, `IndexOf(char)` | high: its own docs call it potentially noisy | | CA1309 | Use ordinal StringComparison | `string.Compare` and `Equals` calls that do not specify `Ordinal` or `OrdinalIgnoreCase`, whether they pass no comparison or a deliberate `CurrentCulture` | depends on how much display code you have | Running them on a small file confirms the split: `user.StartsWith("adm")` raises CA1310, `user.Contains("min")` and `user.IndexOf('m')` raise only CA1307, `user.Equals("admin")` raises CA1307 and CA1309, and `string.Compare(user, "admin", StringComparison.CurrentCulture)` raises CA1309 even though the culture was chosen on purpose. A parameterless `ToUpper()` raises CA1311 and also CA1304 ("Specify CultureInfo"). ## Where I would land 1. **CA1310 and CA1311 as errors everywhere.** They point at exactly the calls whose behaviour changes with the server's culture, the source of Turkish-i and ignorable-character bugs, and the fixes are mechanical. 2. **CA1307 only if the team wants total explicitness.** It turns every `Contains` and `Equals` into a required edit. Some teams like that, because every comparison becomes greppable; others find it churn without bugs. Decide once, not per pull request. 3. **CA1309 per project.** In a backend service with no display code it is a useful tripwire: any culture-aware comparison must be suppressed with a justification. In a UI or reporting project it fires on correct code, so set it to `none` there. 4. **Roll out as warnings first,** fix or suppress existing hits with `#pragma warning disable` or `[SuppressMessage]` and a reason, then raise the severity to `error`. Enforcement is plain configuration, for example in `.editorconfig`: ```ini [*.cs] dotnet_diagnostic.CA1310.severity = error dotnet_diagnostic.CA1311.severity = error dotnet_diagnostic.CA1307.severity = suggestion ``` Setting a severity there is enough to turn a rule on. The .NET docs also show the project-file route: `<AnalysisMode>All</AnalysisMode>` plus `CA1307;CA1309;CA1310` in `<WarningsAsErrors>`. ## What the analyzers do not cover - **Sorting without a comparer.** `List<string>.Sort()` and `OrderBy(s => s)` use `Comparer<string>.Default`, which is culture-aware, and none of these rules flag them. - **Collections built without a comparer.** `new Dictionary<string, T>()` is ordinal and case-sensitive; whether case-insensitivity was needed is a design question no rule answers. - **Which culture.** The analyzers make you write `CurrentCulture`; they cannot tell you that a server's culture is the wrong one for an email rendered for a user in another country. ## The alternative some services take A service that never shows text to people can opt into **invariant globalization mode** (`<InvariantGlobalization>true</InvariantGlobalization>`). The docs state that in that mode linguistic operations behave as `Ordinal` or `OrdinalIgnoreCase` whatever `CultureInfo` or `StringComparison` is passed. That removes the whole bug class at the cost of any culture-aware behaviour, so it is a per-service decision, not a substitute for the coding rule.

  • Why not simply enable CA1307 as an error in every project?
    Because it flags calls that are already ordinal, such as `Contains(string)`, `Equals(string)` and `IndexOf(char)`, so most hits are edits that change no behaviour. Its own documentation points to CA1310 for teams that want only culture-default calls flagged. It is worth it only if the team values every comparison being explicit and searchable.
  • Which comparison bugs slip past all four rules?
    Sorting with `List<string>.Sort()` or `OrderBy(s => s)`, which use the culture-aware `Comparer<string>.Default`; keyed collections created without the comparer the data needs; and code that names `CurrentCulture` when it should have used a specific user's culture. Those need review or a shared helper, not an analyzer.
  • When is CurrentCulture legitimate inside a backend service?
    When the service produces text for a person: an email, a PDF report or an export that a user sorts by eye. Even then, pass that user's `CultureInfo` explicitly instead of relying on the server's current culture, which reflects where the code runs, not who reads it.

  • The globalization analyzers are on by default, so nothing needs configuring.
  • CA1307 and CA1310 flag the same calls, so enabling either is equivalent.
  • A CA1309 warning on an explicit CurrentCulture comparison always means a bug.
  • Once the analyzers pass, every string sort in the codebase is culture-safe.
  • InvariantCulture is the right team-wide default because it never changes between servers.