In .NET, which string methods compare with the current culture when you pass no StringComparison, and which compare ordinally?
answer
- char overloads versus string overloads
- ordering methods versus equality methods
- Contains and IndexOf disagree
- invisible characters can be skipped
- Sort uses CompareTo
basics
~10 sOrdinal by default: ==, Equals, Contains, Replace and every char overload. Current culture by default: CompareTo, string.Compare, StartsWith(string), EndsWith(string), IndexOf(string) and LastIndexOf(string), plus ToUpper and ToLower casing and List<string>.Sort().
solid answer
~40 sEquality is ordinal: `==`, `Equals(string)` and static `string.Equals(a, b)` compare code units. So do `Contains(string)`, `Replace(string, string)` and every overload that takes a `char`, such as `IndexOf(char)` and `StartsWith(char)`. Ordering and substring search with a string argument are culture-aware: `CompareTo`, `string.Compare(a, b)`, `StartsWith(string)`, `EndsWith(string)`, `IndexOf(string)` and `LastIndexOf(string)` use `CultureInfo.CurrentCulture`, and so do `ToUpper()` and `ToLower()`. `List<string>.Sort()` and `OrderBy(s => s)` go through `Comparer<string>.Default`, which calls `CompareTo`. The mismatch has visible effects: with ICU, a soft hyphen is ignored by linguistic comparison, so `string.Compare("co\u00ADop", "coop")` returns 0 while `==` returns false, and rewriting `s.Contains(x)` as `s.IndexOf(x) >= 0` silently switches from ordinal to culture-aware. The cure is to pass a `StringComparison` every time.
code
csharp · 16 linesusing System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");
string stored = "coop"; // "coop" with an invisible soft hyphen (U+00AD)
string typed = "coop";
Console.WriteLine(stored == typed); // ordinal
Console.WriteLine(stored.Equals(typed)); // ordinal
Console.WriteLine(string.Compare(stored, typed)); // current culture
Console.WriteLine(stored.CompareTo(typed)); // current culture
Console.WriteLine(stored.StartsWith("coo")); // current culture
Console.WriteLine(stored.IndexOf("oop")); // current culture
Console.WriteLine(stored.Contains("oop")); // ordinal
Console.WriteLine("hello".IndexOf("")); // current culture, zero-width joiner
Console.WriteLine("hello".IndexOf("", StringComparison.Ordinal));go deeper
Remember the split: equality, Contains and char overloads are ordinal; CompareTo, StartsWith(string) and IndexOf(string) use the current culture.
Explain why a linguistic comparison can return 0 for strings that differ in code units, and show that Sort() inherits the culture through CompareTo.
Spot the refactoring and parsing bugs this causes, such as IndexOf(string) finding a delimiter differently from Contains, and fix them by passing StringComparison explicitly.
Use the inconsistency as the argument for a rule that every call names its comparison, so nobody has to remember which overload defaults to what.
## Two defaults in one class `System.String` has no single default comparison. Each method family has its own, and the split catches people every year. The reference source makes it plain: `StartsWith(string value)` is literally `StartsWith(value, StringComparison.CurrentCulture)`, `CompareTo(string)` is `Compare(this, strB, StringComparison.CurrentCulture)`, and `operator ==` calls the ordinal `Equals(a, b)`. | Call with no `StringComparison` | Default | |---|---| | `a == b`, `a.Equals(b)`, `string.Equals(a, b)` | ordinal | | `Contains(string)`, `Contains(char)` | ordinal | | `Replace(string, string)` | ordinal | | `IndexOf(char)`, `LastIndexOf(char)`, `StartsWith(char)`, `EndsWith(char)` | ordinal | | `IndexOf(string)`, `LastIndexOf(string)` | current culture | | `StartsWith(string)`, `EndsWith(string)` | current culture | | `CompareTo(string)`, `string.Compare(a, b)` | current culture | | `ToUpper()`, `ToLower()` | current culture casing | | `List<string>.Sort()`, `Array.Sort(string[])`, `OrderBy(s => s)` | `Comparer<string>.Default`, which calls `CompareTo`: current culture | A useful way to remember it: - **Equality and containment are ordinal.** "Are these the same characters?" is answered by code units. - **Ordering is culture-aware.** `CompareTo` and `Compare` exist to sort, and sorting for people is linguistic. - **Substring search with a `string` argument is culture-aware**, except `Contains`, which is ordinal. With a `char` argument, everything is ordinal. ## What "culture-aware" does to real strings A linguistic comparison does not compare characters one by one; it compares collation elements, and some characters carry **zero weight**. Since .NET 5, .NET uses ICU for this on every supported platform, and ICU treats the soft hyphen (U+00AD), the zero-width joiner (U+200D) and the null character as ignorable. That produces results that look impossible if you assume ordinal: ```csharp string stored = "co\u00ADop"; // "coop" with a soft hyphen bool same = stored == "coop"; // false: different code units int order = string.Compare(stored, "coop"); // 0: the soft hyphen has no weight int at = stored.IndexOf("oop"); // 1: matches across the hyphen bool has = stored.Contains("oop"); // false: ordinal substring search int zwj = "hello".IndexOf("\u200D"); // 0: an ignorable string matches at the start ``` So a username that contains an invisible character can sort as a duplicate of another, and parsing code that calls `IndexOf(string)` to find a delimiter can get a different answer than `Contains` gives for the same input. The .NET security guidance says to use ordinal comparisons for any filtering or access-control decision for exactly this reason. ## CompareTo, Compare, Equals and == These four are often treated as interchangeable. They are not: 1. **`==` and `Equals(string)`** answer "same code units?" and are ordinal. (What `==` means when the operands are typed as `object` is a question about equality and reference types, covered with equality.) 2. **`CompareTo(string)`** returns a sign for sort order using the current culture. It has **no** `StringComparison` overload; use `string.Compare(a, b, comparisonType)` or a `StringComparer` instead. 3. **`string.Compare(a, b)`** is the static form, also current culture by default. 4. **Testing `Compare(...) == 0` for equality** is a mistake the .NET guidance calls out: under a linguistic comparison, "equal" means "same collation weight", not "same text". ## Sorting picks up the culture too `names.Sort()` with no argument uses `Comparer<string>.Default`, which ends in `CompareTo`. Under `en-US`, `{ "banana", "Apricot", "cherry", "apricot" }` sorts to `apricot, Apricot, banana, cherry`; with `StringComparer.Ordinal` it sorts to `Apricot, apricot, banana, cherry` because `'A'` (65) is below `'a'` (97). Neither is wrong; they answer different questions. What is wrong is not choosing: a sorted list of keys used for a binary search, or a merge of two sorted files, needs the same ordinal comparer on both sides. ## Where it bites in practice The defaults rarely matter for plain ASCII words, which is why the bugs survive testing. They surface with real input: 1. **Parsing user-supplied text.** Code that finds a delimiter with `IndexOf(string)` and slices with the result can be steered by invisible characters: the culture-aware search matches across them, so the matched text can be longer than the search string, and slicing with the search string's `Length` cuts in the wrong place. 2. **Suffix and prefix checks.** Under ICU, `"hello".EndsWith("")` is `true`: an ignorable suffix "matches" any string. A file-type or scheme check written with `EndsWith(string)` or `StartsWith(string)` inherits that, plus the server's culture. 3. **Refactoring.** Swapping `Contains` for `IndexOf`, or `==` for `string.Compare(...) == 0`, changes ordinal into culture-aware without any visible change in the code's intent. ## The fix - Pass a `StringComparison` to every string method that accepts one, including the ones whose default is already what you want; the call site then documents its intent. - Pass a `StringComparer` to `Sort`, `OrderBy`, `Dictionary` and `HashSet`. - Reach for `CurrentCulture` deliberately, for text a person will read, and `Ordinal` or `OrdinalIgnoreCase` everywhere else.
- If you rewrite s.Contains(x) as s.IndexOf(x) >= 0, what changes?The comparison changes from ordinal to current-culture. `IndexOf(string)` can now match across ignorable characters, can report a match for a search string made only of zero-weight characters, and depends on the server's culture. Write `s.IndexOf(x, StringComparison.Ordinal) >= 0` to keep the original meaning.
- Why can "hello".IndexOf("\u200D") return 0 when the string has no zero-width joiner?`IndexOf(string)` is a culture-aware search, and with ICU the zero-width joiner has no collation weight, so searching for it is like searching for an empty string, which matches at index 0. The ordinal overload, `IndexOf("\u200D", StringComparison.Ordinal)`, returns -1.
- How do you compare two strings for sort order without the current culture, given that CompareTo has no StringComparison overload?Call `string.Compare(a, b, StringComparison.Ordinal)` (or `string.CompareOrdinal(a, b)`), or use `StringComparer.Ordinal.Compare(a, b)`. For sorting collections, pass the comparer: `list.Sort(StringComparer.Ordinal)` or `OrderBy(s => s, StringComparer.Ordinal)`.
- Every string method in .NET compares ordinally unless you pass a culture.
- s.Contains(x) and s.IndexOf(x) >= 0 always give the same answer.
- CompareTo returning 0 proves the two strings hold the same characters.
- List<string>.Sort() with no comparer sorts by character code.
- The char and string overloads of IndexOf use the same default comparison.