Search code examples
c#dictionarystring-comparison

Default StringComparer used by Dictionary<string, T>


I'm used to specifying a StringComparer whenever creating a Dictionary keyed by string and I'm wondering what comparer gets used if none is specified. The docs say

This constructor uses the default generic equality comparer, EqualityComparer.Default

Debugging revealed the run-time type of System.Collections.Generic.GenericEqualityComparer<string> but I couldn't find any documentation on it.

What does it do? Does it match any of the pre-defined StringComparers like Ordinal or CurrentCulture?


Solution

  • The short answer is Ordinal but proving that took some digging around.

    Firstly, the docs for Dictionary's default constructor say:

    Initializes a new instance of the Dictionary<TKey,TValue> class that [...] uses the default equality comparer for the key type.

    EqualityComparer.Default docs say:

    The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparer that uses that implementation. Otherwise, it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

    Since System.String does not implement System.IEquatable, Default should use its Object.Equals and Object.GetHashCode which perform the Ordinal comparison:

    Remarks

    This method performs an ordinal (case-sensitive and culture-insensitive) comparison.