Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between string.GetHashCode and IEqualityComparer<string>.Default.GetHashCode

Tags:

c#

.net

I would like to use Distinct() with my data, declared as IEnumerable<KeyValuePair<IdentType, string>>. In this case, i have to implement my own IEqualityComparer and there is my question:

Is there any difference between below implementations?

public int GetHashCode(KeyValuePair<IdentType, string> obj) {
    return EqualityComparer<string>.Default.GetHashCode(obj.Value);
}

and

public int GetHashCode(KeyValuePair<IdentType, string> obj) {
    return obj.Value.GetHashCode();
}
like image 962
Maxim Zhukov Avatar asked Dec 08 '22 05:12

Maxim Zhukov


2 Answers

There is only a small difference between your two methods.

EqualityComparer<string>.Default will return a class of type GenericEqualityComparer<T> if the class implments IEquateable<T> (which string does). So that GetHashCode(obj.Value) gets called to

    public override int GetHashCode(T obj) {
        if (obj == null) return 0;
        return obj.GetHashCode();
    }

which is the same as you calling obj.Value.GetHashCode(); directly, except for the fact that if you have a null string the default comparer will return 0 and the direct call version will throw a null reference exception.

like image 65
Scott Chamberlain Avatar answered Dec 11 '22 07:12

Scott Chamberlain


Just one: the equality comparer's GetHashCode will return 0 if the string is null, whereas the second implementation will throw an exception.

like image 25
dcastro Avatar answered Dec 11 '22 07:12

dcastro