Search code examples
c#dictionarykeycase-sensitive

Case Sensitive Dictionary Keys


I've found plenty of info on the web about making dictionaries able to do case insensitive look-ups such that if I added a key/value pair of ("A", "value") calling

MyDict["a"] == MyDict["A"]

will return true.

What I want to know is why I get a "key has already been added" error when I do

MyDict.Add("A", "value1");
MyDict.Add("a", "value2");

if I defined my dictionary to do case sensitive look-ups. Is there no way to define a Dictionary to be able to add different cased keys?


Solution

  • Dictionaries are case-sensitive by default - you don't need to do anything.

    Dictionary<string, string> myDict = new Dictionary<string, string>();
    myDict.Add("A", "value1");
    myDict.Add("a", "value2");
    

    See your code working online here: ideone.

    If you are getting an error with your code then it's because one of those keys already exist in your dictionary.