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();
}
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.
Just one: the equality comparer's GetHashCode
will return 0 if the string is null, whereas the second implementation will throw an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With