C# Case insensitive dictionary

By FoxLearn 1/21/2025 6:19:37 AM   10
Dictionaries in C# are case sensitive by default when using string keys.

If you need a case-insensitive dictionary, you can specify a StringComparer when creating the dictionary.

For example, using StringComparer.OrdinalIgnoreCase will make the dictionary ignore case differences.

var myDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

Imagine you are working on a system where you manage customer subscriptions. Each customer is identified by their email address. Since email addresses are case-insensitive, a case-sensitive dictionary could lead to errors (e.g., treating "[email protected]" and "[email protected]" as different customers).

To avoid this, you can use a case-insensitive dictionary.

var subscriptionMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    { "[email protected]", "Premium" },
    { "[email protected]", "Standard" }
};

// Accessing the value with different cases:
Console.WriteLine(subscriptionMap["[email protected]"]); // Output: Premium
Console.WriteLine(subscriptionMap["[email protected]"]); // Output: Standard

Why Use Case Insensitivity?

By using a case-insensitive dictionary, you ensure consistent behavior regardless of how keys are provided or stored, which can prevent potential bugs caused by case mismatches.

C# offers multiple case-insensitive options:

  • StringComparer.InvariantCultureIgnoreCase
  • StringComparer.OrdinalIgnoreCase
  • StringComparer.CurrentCultureIgnoreCase