Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 12

    Choosing Ordinal Comparers for Dictionary and HashSet

    Lesson video

    Should letter case change which item you find?

    Say your stock list has eight units under SKU-42. Then a feed reports twelve units under sku-42. Is that an update to the same product or a count for a different product? The answer comes from your inventory system's rules, not from what the strings look like.

    A string comparer tells the dictionary which spellings count as the same key. StringComparer.Ordinal is case-sensitive and does not follow the rules of a language. StringComparer.OrdinalIgnoreCase also ignores language rules, but treats case differences such as SKU and sku as equal. Neither trims spaces or rewrites the keys.

    C#
    var exact = new Dictionary<string, int>(StringComparer.Ordinal)
        { ["SKU-42"] = 8 };
    var ignoreCase = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
        { ["SKU-42"] = 8 };
    
    exact["sku-42"] = 12;
    ignoreCase["sku-42"] = 12;
    • Case matters: exact has two entries. Looking up SKU-42 gives 8; looking up sku-42 gives 12.
    • Case does not matter: ignoreCase has one entry. Either spelling finds the updated value, 12.

    The comparer decides whether the key matches. The operation decides what to do with a match. Assignment with map[key] = value updates a match or inserts a new key. Dictionary.Add throws if the key already exists; HashSet.Add returns false if the item is already present. Use the rule your data requires, then follow the complete example below to see both collections in action.

    Run and inspect the complete example

    Run this example

    Use the .NET 10 SDK. In a new empty folder, save the project below as Example.csproj and the listing as Program.cs. Run dotnet run --project Example.csproj.

    XML
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <ImplicitUsings>disable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
    </Project>

    Comparer policy changes lookup and uniqueness

    Program.cs

    C#
    using System;
    using System.Collections.Generic;
    
    internal static class Program
    {
        private static void Main()
        {
            var cases = new[] { ("api", "API"), ("Content-Type", "content-type") };
    
            var ordinalDict = new Dictionary<string, int>(StringComparer.Ordinal);
            var ignoreCaseDict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
    
            var ordinalSet = new HashSet<string>(StringComparer.Ordinal);
            var ignoreCaseSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
    
            foreach (var (first, second) in cases)
            {
                ordinalDict.Clear();
                ignoreCaseDict.Clear();
                ordinalSet.Clear();
                ignoreCaseSet.Clear();
    
                ordinalDict[first] = 1;
                ordinalDict[second] = 2;
    
                ignoreCaseDict[first] = 1;
                ignoreCaseDict[second] = 2;
    
                bool ordinalAddedFirst = ordinalSet.Add(first);
                bool ordinalAddedSecond = ordinalSet.Add(second);
    
                bool ignoreCaseAddedFirst = ignoreCaseSet.Add(first);
                bool ignoreCaseAddedSecond = ignoreCaseSet.Add(second);
    
                bool policyChecksPass =
                    ordinalDict.Count == 2 && ignoreCaseDict.Count == 1 &&
                    ordinalSet.Count == 2 && ignoreCaseSet.Count == 1 &&
                    ordinalAddedFirst && ordinalAddedSecond &&
                    ignoreCaseAddedFirst && !ignoreCaseAddedSecond &&
                    ordinalDict.ContainsKey(second) && ignoreCaseDict.ContainsKey(second) &&
                    ordinalDict[first] == 1 && ignoreCaseDict[first] == 2;
    
                if (!policyChecksPass)
                {
                    Console.Error.WriteLine("FAIL: comparer policy check failed.");
                    Environment.ExitCode = 1;
                    return;
                }
    
                Console.WriteLine($"Pair: '{first}' vs '{second}'");
                Console.WriteLine($"Ordinal dictionary count = {ordinalDict.Count}");
                Console.WriteLine($"OrdinalIgnoreCase dictionary count = {ignoreCaseDict.Count}");
                Console.WriteLine($"Ordinal set added first = {ordinalAddedFirst}");
                Console.WriteLine($"Ordinal set added second = {ordinalAddedSecond}");
                Console.WriteLine($"OrdinalIgnoreCase set added first = {ignoreCaseAddedFirst}");
                Console.WriteLine($"OrdinalIgnoreCase set added second = {ignoreCaseAddedSecond}");
                Console.WriteLine($"Ordinal lookup for second key exists = {ordinalDict.ContainsKey(second)}");
                Console.WriteLine($"OrdinalIgnoreCase lookup for second key exists = {ignoreCaseDict.ContainsKey(second)}");
                Console.WriteLine($"Ordinal stored value for first key = {ordinalDict[first]}");
                Console.WriteLine($"OrdinalIgnoreCase stored value for first key = {ignoreCaseDict[first]}");
                Console.WriteLine();
            }
    
            Console.WriteLine("PASS: comparer policy controls both lookup and uniqueness.");
        }
    }

    Trace one pair before running

    For api and API, first trace the assignments: ordinal stores two entries; ignore-case updates the first entry to 2. Then trace Add: the ordinal set accepts both strings; the ignore-case set rejects the second. Both lookup lines are True, so those lines alone do not demonstrate the policy difference. Read them together with counts, second-insertion results and the stored value for the first key.

    Expected output

    Both pairs must produce these results. If a policy check fails, the program exits with code 1 and writes a FAIL message instead of printing PASS.

    Text
    Pair: 'api' vs 'API'
    Ordinal dictionary count = 2
    OrdinalIgnoreCase dictionary count = 1
    Ordinal set added first = True
    Ordinal set added second = True
    OrdinalIgnoreCase set added first = True
    OrdinalIgnoreCase set added second = False
    Ordinal lookup for second key exists = True
    OrdinalIgnoreCase lookup for second key exists = True
    Ordinal stored value for first key = 1
    OrdinalIgnoreCase stored value for first key = 2
    
    Pair: 'Content-Type' vs 'content-type'
    Ordinal dictionary count = 2
    OrdinalIgnoreCase dictionary count = 1
    Ordinal set added first = True
    Ordinal set added second = True
    OrdinalIgnoreCase set added first = True
    OrdinalIgnoreCase set added second = False
    Ordinal lookup for second key exists = True
    OrdinalIgnoreCase lookup for second key exists = True
    Ordinal stored value for first key = 1
    OrdinalIgnoreCase stored value for first key = 2
    
    PASS: comparer policy controls both lookup and uniqueness.

    The collection owns the string policy

    For most backend identifiers, machine-generated names, route segments, protocol tokens, and configuration keys, ordinal comparison is the safest default because it compares the underlying UTF-16 code units directly rather than applying culture rules. This avoids dependence on the current user locale. Case-insensitive Unicode matching can still evolve with runtime Unicode data.

    Be precise about the default: Dictionary<string, TValue> and HashSet<string> use EqualityComparer<string>.Default unless you supply a comparer. In practice, that default behaves like ordinal case-sensitive equality for strings, but it is better to choose the comparer explicitly when the intent matters.

    The most important rule is consistency: if your dictionary uses StringComparer.OrdinalIgnoreCase, then both lookup and uniqueness are case-insensitive. You do not get to choose case-insensitive lookup and case-sensitive uniqueness separately inside the same collection.

    HashSet<string> follows the same policy model as Dictionary<string, TValue>:

    • Add returns true when a new element was inserted.
    • Add returns false when the comparer says the element is already present.
    • Contains uses the comparer, not a raw == comparison.
    • Remove also uses the comparer.

    That means the comparer changes the definition of “same key” for the entire collection.

    Failure modes

    Common mistakes in interviews and production code include:

    1. Using the default comparer without checking semantics

    The default comparer for string keys is not something to guess about in important code. Choose the comparer explicitly when the key meaning matters.

    1. Using culture-sensitive comparison for identifiers

    Culture-aware comparison is for human text, not protocol keys. It can make lookups depend on the current culture, which is usually a bug for backend systems.

    1. Assuming comparer choice affects only lookup, not uniqueness

    In HashSet<string>, comparer policy directly controls what duplicates exist. In Dictionary<string, TValue>, it controls whether a later assignment replaces an existing entry.

    1. Mixing comparer policy across layers

    If a service normalizes keys one way but the collection compares them another way, you can get invisible collisions or failed lookups.

    1. Treating ordinal as “ASCII only”

    Ordinal means code-unit comparison, not limited to ASCII. It simply does not apply linguistic rules.

    Explain the observed collection results

    Answer against the complete fixture, then compare with the responses.

    1. Why use StringComparer.OrdinalIgnoreCase for HTTP header names?
    2. What changes in a case-insensitive set?
    3. How can the same two strings behave differently in two dictionaries?
    4. When is current-culture comparison a poor fit?
    5. Why does the comparer affect both lookup and uniqueness?
    6. Why choose Ordinal explicitly if the string default is already case-sensitive?

    Hint: Decide whether the keys match before deciding what assignment or Add does.

    Worked responses

    1. HTTP field names ignore letter case. In this example, Content-Type and content-type therefore identify one name. Do not apply that rule automatically to field values or unrelated identifiers.
    2. For api followed by API, the first Add returns True, the second returns False, and the count is 1.
    3. The ordinal dictionary keeps values 1 and 2 in two entries. The ignore-case dictionary treats the second assignment as an update; one entry remains with value 2.
    4. For this header-name collection, changing the reader's language should not change which entry the request finds. Use the protocol's matching rule.
    5. If API finds the entry inserted as api, adding API must also recognize that existing entry. The two operations cannot use contradictory definitions of a duplicate.
    6. In this listing it documents the intended contrast with the ignore-case collection. It is an explicit policy choice, not an extra normalization step.

    Which comparer for which key

    Identifiers, config keys, protocol tokens
    StringComparer.Ordinal "api" and "API" are two keys
    Case-insensitive names, such as HTTP header names
    StringComparer.OrdinalIgnoreCase "Content-Type" and "content-type" are one key
    Human text shown to readers
    Culture-aware comparison, not for backend keys Results can depend on the current culture
    Whole collection
    One comparer drives Add, Contains, Remove and lookup A rejected Add and a successful lookup agree

    Code walkthrough

    The program builds two dictionaries and two sets with different comparer policies.

    • With StringComparer.Ordinal, "api" and "API" are different keys.
    • With StringComparer.OrdinalIgnoreCase, those same strings collapse to one logical key.
    • The Count values demonstrate uniqueness rules.
    • The ContainsKey checks demonstrate lookup rules.
    • The HashSet.Add results show whether the second value was inserted or rejected as a duplicate.

    The final PASS is printed only after both pairs satisfy the count, insertion, lookup, and replacement checks. Notice that the code does not rely on numeric hash codes or iteration order. That is intentional: interview-relevant behavior here is semantic, not dependent on implementation details.

    Quick reference: predict the operation, then the policy

    Use the lesson's ordinal and ignore-case comparison side by side. For a dictionary already containing job with value 4 under StringComparer.OrdinalIgnoreCase:

    • map["JOB"] = 9 updates the matching entry. Count stays 1; map["JoB"] reads 9.
    • map.Add("JOB", 9) rejects the duplicate with ArgumentException; the existing value remains 4 if the exception is caught.
    • map.TryAdd("JOB", 9) returns false and leaves the value at 4.

    These are three alternative operations from the same starting state, not a sequence. The comparer decides whether a match exists; the operation decides what to do with that match.

    For an ignore-case set containing job, Add("JOB") returns false, Contains("JoB") returns true, and Remove("JOB") removes that entry.

    A lookup check that shows the difference

    The main example inserts both spellings before checking the second. Its counts and replacement results correctly show the contrast, but both lookup checks succeed. To isolate lookup alone, insert only one spelling:

    C#
    var exact = new HashSet<string>(StringComparer.Ordinal) { "job" };
    var folded = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "job" };
    Console.WriteLine(exact.Contains("JOB"));
    Console.WriteLine(folded.Contains("JOB"));

    Expected output:

    Text
    False
    True

    Three interview boundaries

    1. Choose the rule from the data's contract. HTTP field names ignore case; that does not establish the rule for field values or every route, account name, or token.
    2. Ignoring case is not trimming. In the fixture above, adding "job " to folded succeeds because the trailing space remains part of the key.
    3. Rebuilding a dictionary under a different policy may merge previously distinct keys. If an ordinal source contains both job and JOB, the constructor taking that source plus OrdinalIgnoreCase throws for the duplicate. Decide how such conflicts should be handled before migrating data.

    Optional video: collection comparers

    Watch the 7:54–9:29 collection-comparer chapter of Michael Jolley: Stop Using ToLower() for Comparisons!. The free external segment demonstrates StringComparer.OrdinalIgnoreCase with dictionaries and sets. Use this lesson for the precise rule: ordinal comparison uses UTF-16 code units; choose case sensitivity from the key’s contract.

    Check the misconception

    An OrdinalIgnoreCase dictionary already maps job to 4. What does map["JOB"] = 9 do?

    A Adds a second distinct key and keeps job mapped to 4.
    B Throws because the matching key already exists.
    C Updates the matching entry to 9, keeping Count at 1.
    D Trims every stored string before replacing it.
    Show answer

    Correct answer: C

    The comparer treats the spellings as one key, and indexer assignment replaces an existing key's value. Add and TryAdd express different duplicate policies.

    Option A: The case difference does not create a second key under this comparer.

    Option B: Add rejects a duplicate; the indexer setter replaces its value.

    Option D: Ignoring case is not whitespace normalization.

    Hint: Decide whether the key matches before reading the chosen operation.

    API check: Microsoft 1, Microsoft 2.

    Practice

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·