Case-insensitive Dictionary in C#

A case-insensitive Dictionary in C# allows you to perform key lookups without considering the case of string keys. This means keys like "cricket", "CRICKET", and "Cricket" are treated as identical. This is particularly useful when dealing with user input or data from external sources where case consistency cannot be guaranteed.

Syntax

To create a case-insensitive Dictionary, use the StringComparer.OrdinalIgnoreCase parameter in the constructor −

Dictionary<string, TValue> dict = new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase);

You can also use other string comparers −

// Culture-insensitive comparison
Dictionary<string, int> dict1 = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase);

// Current culture ignore case
Dictionary<string, int> dict2 = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);

Using StringComparer.OrdinalIgnoreCase

The most common approach uses StringComparer.OrdinalIgnoreCase which provides fast, culture-insensitive case comparison −

Example

using System;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        Dictionary<string, int> dict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
        
        dict.Add("cricket", 1);
        dict.Add("football", 2);
        dict.Add("tennis", 3);
        
        // Display all items
        Console.WriteLine("Dictionary contents:");
        foreach (var val in dict) {
            Console.WriteLine($"[{val.Key}, {val.Value}]");
        }
        
        // Case insensitive lookup - all variations work
        Console.WriteLine("\nCase-insensitive lookups:");
        Console.WriteLine("dict["cricket"]: " + dict["cricket"]);
        Console.WriteLine("dict["CRICKET"]: " + dict["CRICKET"]);
        Console.WriteLine("dict["Cricket"]: " + dict["Cricket"]);
        
        // ContainsKey is also case-insensitive
        Console.WriteLine("\nContainsKey tests:");
        Console.WriteLine("Contains 'FOOTBALL': " + dict.ContainsKey("FOOTBALL"));
        Console.WriteLine("Contains 'Tennis': " + dict.ContainsKey("Tennis"));
    }
}

The output of the above code is −

Dictionary contents:
[cricket, 1]
[football, 2]
[tennis, 3]

Case-insensitive lookups:
dict["cricket"]: 1
dict["CRICKET"]: 1
dict["Cricket"]: 1

ContainsKey tests:
Contains 'FOOTBALL': True
Contains 'Tennis': True

Comparison of String Comparers

StringComparer Description Best Use Case
OrdinalIgnoreCase Fast, culture-insensitive case comparison General purpose, identifiers, file names
CurrentCultureIgnoreCase Uses current culture rules for comparison User-facing strings in current locale
InvariantCultureIgnoreCase Uses invariant culture rules Data persistence, consistent across cultures

Adding Duplicate Keys with Different Cases

When using a case-insensitive Dictionary, attempting to add keys that differ only in case will throw an exception −

Example

using System;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        Dictionary<string, int> dict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
        
        dict.Add("apple", 1);
        Console.WriteLine("Added 'apple' successfully");
        
        try {
            // This will throw an ArgumentException
            dict.Add("APPLE", 2);
        }
        catch (ArgumentException ex) {
            Console.WriteLine("Exception caught: " + ex.Message);
        }
        
        // Use TryAdd for safe addition (available in .NET Core/5+)
        bool added = dict.TryAdd("ORANGE", 3);
        Console.WriteLine("TryAdd 'ORANGE': " + added);
        
        added = dict.TryAdd("orange", 4);
        Console.WriteLine("TryAdd 'orange': " + added);
        
        Console.WriteLine("\nFinal dictionary:");
        foreach (var item in dict) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

The output of the above code is −

Added 'apple' successfully
Exception caught: An item with the same key has already been added.
TryAdd 'ORANGE': True
TryAdd 'orange': False

Final dictionary:
apple: 1
ORANGE: 3

Conclusion

Case-insensitive Dictionaries in C# are created using string comparers like StringComparer.OrdinalIgnoreCase. They treat string keys with different cases as identical, making them ideal for scenarios where case variations should be ignored. Use OrdinalIgnoreCase for most general purposes as it provides fast, culture-independent comparison.

Updated on: 2026-03-17T07:04:35+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements