Here is the equality comparer I just wrote because I wanted a distinct set of items from a list containing entities.
class InvoiceComparer : IEqualityComparer<Invoice>
{
public bool Equals(Invoice x, Invoice y)
{
// A
if (Object.ReferenceEquals(x, y)) return true;
// B
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false;
// C
return x.TxnID == y.TxnID;
}
public int GetHashCode(Invoice obj)
{
if (Object.ReferenceEquals(obj, null)) return 0;
return obj.TxnID2.GetHashCode();
}
}
- Why does
Distinctrequire a comparer as opposed to aFunc<T,T,bool>? - Are (A) and (B) anything other than optimizations, and are there scenarios when they would not act the expected way, due to subtleness in comparing references?
-
If I wanted to, could I replace (C) with
return GetHashCode(x) == GetHashCode(y)
(B) is necessary; otherwise, it would throw an
NullReferenceException.If
Invoiceis a struct, however, they’re both unnecessary and slower.