C# / CHAPTER 09

Dictionary contracts and equality rules

Intermediate

Keep missing keys distinct from stored default values.

By the end of this chapter

  • Choose a key comparer
  • Use TryGetValue for expected absence
  • Count values without duplicate-key exceptions

The idea

A Dictionary<TKey,TValue> associates unique keys with values under an equality comparer. For textual identifiers, choose case sensitivity intentionally. StringComparer.OrdinalIgnoreCase is useful when a technical identifier should ignore case without applying a culture-specific sorting policy. The comparer is part of the collection’s contract, not a display preference.

TryGetValue reports presence separately from the returned value. A missing integer value and a stored zero can both produce zero in the out variable, so the boolean result matters. The indexer getter throws for absence; its setter adds or replaces. Add rejects an existing key. Use these distinct behaviors deliberately when counting, updating, or detecting duplicates.

C# example
using System;
using System.Collections.Generic;
var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var word in new[] {"Red", "red", "Blue"}) {
  counts.TryGetValue(word, out int old);
  counts[word] = old + 1;
}
Console.WriteLine($"{counts.Count} {counts["RED"]}");
Result
2 2

Red, red, and RED identify the same key under the supplied comparer.

Try it yourself

Build a case-insensitive inventory that rejects duplicate creation but permits explicit updates.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which part distinguishes an absent key from a present integer value of zero?