Pergunta

It's my understanding that key checks in Dictionary are case sensitive by default but it appears, at least in my software that this isn't the case. In order to get a case sensitive key check for TryGetValue and Contains, I have to construct my Dictionary as follows:

Dictionary<string, string> a = new Dictionary<string,string>(StringComparer.Ordinal);

So was I wrong about this? Is dictionary case-insensitive by default?

Foi útil?

Solução

No, Dictionary<string, string> is not case-insensitive by default.

This can be easily shown with this little application:

using System;
using System.Collections.Generic;

public class MainClass
{
    public static void Main(string[] args)
    {
        var newDict = new Dictionary<string, string>();
        newDict.Add("a", "x");
        Console.WriteLine(newDict.ContainsKey("a"));
        Console.WriteLine(newDict.ContainsKey("A"));
        newDict.Add("A", "y");
        Console.WriteLine(newDict.ContainsKey("a"));
        Console.WriteLine(newDict.ContainsKey("A"));
        Console.WriteLine(newDict.Count);
    }
}

This outputs:

True
False
True
True
2

Explanation:

  • At first, key a is added.
  • ContainsKey is used to check whether keys a and A are found. Only the former is.
  • Then, Add is used to add key A. It does not complain, i.e. it does not think that key already exists.
  • In the end, Count is used to check for the total number of dictionary entries and it correctly outputs 2, namely A and a.

Outras dicas

A generic dictionary constructor IDictionary<TKey, TValue>() will use whatever implementation of bool Equals(object obj) and int GetHashCode() is provided on the instances of TKey.

For string this implementation is functionaly equivalent to the implementation provided by EqualityComparer<string>.Default which is functionality equivalent to StringComparer.Ordinal.


As you state in the question, you can use an alternative overload of the dictionary constructor to supply an IEqualityComparer<string> implementation that will be used as an alternative.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top