How do you make a C# Dictionary<string, TValue> or HashSet<string> match keys case-insensitively, and why pass StringComparer.OrdinalIgnoreCase instead of lowercasing keys?
answer
- the constructor takes a comparer
- equality and hash code together
- fixed when the collection is built
- first spelling wins
- copies do not inherit it
basics
~10 sPass StringComparer.OrdinalIgnoreCase to the constructor: new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase). It hashes and compares case-insensitively with no allocations, keeps the original key spelling, and avoids the culture traps of ToLower().
solid answer
~40 s`Dictionary<TKey,TValue>` and `HashSet<T>` take an `IEqualityComparer<T>` in their constructors, and `StringComparer` implements `IEqualityComparer<string?>`, so `new HashSet<string>(StringComparer.OrdinalIgnoreCase)` makes `"Admin"` and `"ADMIN"` the same element. The comparer supplies both `Equals` and `GetHashCode`, consistently, and it is fixed for the collection's lifetime. Lowercasing keys instead allocates a new string on every add and lookup, relies on every call site remembering to do it, loses the spelling the user typed, and if it uses `ToLower()` it follows the current culture, so under `tr-TR` `"MAIL"` becomes `"maıl"`. Two traps remain: a comparer built from `StringComparer.CurrentCultureIgnoreCase` makes lookups culture-dependent, and `new Dictionary<string, int>(existing)` does not copy the source's comparer unless you pass `existing.Comparer`.
code
csharp · 18 linesusing System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
var blocked = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "admin", "root", "mail" };
Console.WriteLine(blocked.Contains("ADMIN")); // True
Console.WriteLine(blocked.Contains("Mail")); // True
var cultureSet = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase) { "admin", "mail" };
Console.WriteLine(cultureSet.Contains("ADMIN")); // False under tr-TR
var accounts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
accounts["Deniz"] = 1;
accounts["DENIZ"] = 2; // same key: overwrites the value
Console.WriteLine($"{accounts.Count} {string.Join(",", accounts.Keys)} {accounts["deniz"]}");
try { accounts.Add("deniz", 3); }
catch (ArgumentException ex) { Console.WriteLine(ex.GetType().Name); }go deeper
Know that Dictionary and HashSet take a comparer in the constructor, and that StringComparer.OrdinalIgnoreCase is the one for case-insensitive keys.
Explain that the comparer supplies both GetHashCode and Equals, why lowercasing keys allocates and leaks the culture, and that the first inserted spelling is kept.
Catch the production traps: copies that drop the comparer, culture-aware comparers that differ per server, and linguistic comparers merging keys with invisible characters.
Make comparer choice part of the team's conventions for keyed collections, so string keys always state ordinal or ordinal-ignore-case at construction.
## The comparer is part of the collection Hash-based collections need two operations on a key: a **hash code** to choose a bucket and an **equality test** to confirm a match. `Dictionary<TKey,TValue>` and `HashSet<T>` get both from an `IEqualityComparer<T>`. When you pass none, a `string` key uses ordinal, case-sensitive equality, so `"Admin"` and `"admin"` are two different keys. `System.StringComparer` is an abstract class that implements `IComparer<string?>`, `IEqualityComparer<string?>` and their non-generic forms, and it exposes six ready-made instances that mirror the `StringComparison` values: `Ordinal`, `OrdinalIgnoreCase`, `InvariantCulture`, `InvariantCultureIgnoreCase`, `CurrentCulture` and `CurrentCultureIgnoreCase`. (`StringComparer.FromComparison(StringComparison)` converts an enum value into one.) For keys, the one you almost always want is `OrdinalIgnoreCase`: ```csharp var blocked = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "admin", "root", "mail" }; blocked.Contains("ADMIN"); // true blocked.Contains("Mail"); // true ``` The same comparer works wherever a collection or a LINQ operator accepts one: `ToDictionary(..., StringComparer.OrdinalIgnoreCase)`, `ToHashSet(StringComparer.OrdinalIgnoreCase)`, `GroupBy`, `Distinct`. Because `StringComparer` is also an `IComparer<string>`, it serves `SortedDictionary<TKey,TValue>`, `SortedSet<T>` and `List<string>.Sort` too. ## Why not lowercase the keys? Normalizing every key with `ToLower()` before using it "works", but it trades one constructor argument for a set of problems: - **Allocation on every operation.** Each `Add`, `ContainsKey` and `TryGetValue` creates a new lowercased string first. The comparer folds case while hashing and comparing and allocates nothing. - **Every call site must remember.** One forgotten `ToLower()` in a new endpoint gives a silent miss. A comparer is a property of the collection, so no caller can bypass it. - **The culture leaks in.** `ToLower()` uses `CultureInfo.CurrentCulture`. Under `tr-TR`, `"MAIL".ToLower()` is `"maıl"` with a dotless ı, so a key added on one server is not found on another. `ToLowerInvariant()` fixes the culture, but not the other points. - **The original spelling is lost.** If the dictionary's keys are shown back to users or logged, you see the folded form, not what was typed. ## How the comparer behaves A few behaviours are worth knowing before code review asks: 1. **First spelling wins.** With `OrdinalIgnoreCase`, `accounts["Deniz"] = 1; accounts["DENIZ"] = 2;` leaves one entry whose key is still `"Deniz"` and whose value is 2: the indexer found the existing key and replaced only the value. 2. **`Add` throws on a case-only duplicate.** `accounts.Add("deniz", 3)` throws `ArgumentException`, because the key already exists under that comparer. 3. **The comparer is fixed at construction.** There is no setter; the `Comparer` property only reports it. To change it, build a new collection. 4. **Copies do not inherit it.** `new Dictionary<string, int>(accounts)` uses the default ordinal comparer, so the copy is case-sensitive again; write `new Dictionary<string, int>(accounts, accounts.Comparer)`. ## The culture-aware comparers are a trap for keys `StringComparer.CurrentCultureIgnoreCase` looks like a case-insensitive comparer, but its notion of "same letter" belongs to a language: | Comparer | `"admin"` vs `"ADMIN"` under `tr-TR` | Depends on server culture? | |---|---|---| | `StringComparer.OrdinalIgnoreCase` | equal | no | | `StringComparer.InvariantCultureIgnoreCase` | equal | no, but still linguistic | | `StringComparer.CurrentCultureIgnoreCase` | **not equal** | yes | The `CurrentCulture` and `CurrentCultureIgnoreCase` properties build a new comparer from `CultureInfo.CurrentCulture` at the moment you read them, so a set created during start-up keeps that start-up culture for its lifetime. And a linguistic comparer can merge keys that differ in stored code units: a `SortedDictionary<string, int>` built with `StringComparer.CurrentCulture` rejects `"co\u00ADop"` (with a soft hyphen) as a duplicate of `"coop"`, because ICU gives the soft hyphen no weight. ## Choosing the comparer for real keys For a user-account service the choices are short: - **Usernames, email domains, role names, HTTP header names:** `StringComparer.OrdinalIgnoreCase`. - **API keys, tokens, case-sensitive identifiers:** the default, or `StringComparer.Ordinal` written out so the choice is visible. - **Display names sorted for a person:** an ordinal-keyed dictionary for lookup, and a culture-aware comparer only when you sort the values for display. Writing the comparer at the construction site, even when it equals the default, tells the next reader that someone decided. ## What OrdinalIgnoreCase does not do `OrdinalIgnoreCase` folds case with the invariant casing table and never expands or merges letters. It does not equate `"straße"` with `"STRASSE"`, `"resume"` with `"résumé"`, or the Turkish `"ı"` with `"I"`. For identifiers that is the right behaviour; for matching words people type, a culture-aware comparison against the user's own culture is the tool, and it belongs in search code, not in a dictionary of keys.
- What happens to case-insensitivity when you copy the dictionary with new Dictionary<string, int>(existing)?It is lost. The copy constructor that takes only an `IDictionary<TKey,TValue>` uses the default comparer, which for `string` is ordinal and case-sensitive, so `copy.ContainsKey("DENIZ")` returns false. Pass the source's comparer explicitly: `new Dictionary<string, int>(existing, existing.Comparer)`.
- Why can a SortedDictionary<string, int> built with StringComparer.CurrentCulture reject a key you never added?A sorted dictionary treats `Compare(a, b) == 0` as the same key. A linguistic comparer gives zero weight to characters such as the soft hyphen, so `"co\u00ADop"` compares equal to `"coop"` and `Add` throws `ArgumentException`. Keys need an ordinal comparer even in a sorted collection.
- Does StringComparer.CurrentCultureIgnoreCase follow later changes to CultureInfo.CurrentCulture?No. Reading the property creates a comparer bound to the culture current at that moment. A set built during start-up under `en-US` keeps comparing with `en-US` after the thread's culture changes; only a comparer read later picks up the new culture.
- Lowercasing every key with ToLower() is the clean way to get case-insensitive lookups.
- You can switch a Dictionary to case-insensitive later by setting its Comparer.
- Copying a case-insensitive Dictionary with its copy constructor keeps the comparer.
- CurrentCultureIgnoreCase is the right comparer for usernames because it understands every language.
- OrdinalIgnoreCase makes straße and STRASSE the same key.