Skip to content

Commit

Permalink
Add proper reference-comparison semantics to CustomEqualityComparer
Browse files Browse the repository at this point in the history
  • Loading branch information
cdhowie committed Sep 16, 2012
1 parent 495711c commit e2576b6
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions Cdh.Toolkit.Collections/CustomEqualityComparer.cs
Expand Up @@ -47,11 +47,32 @@ public CustomEqualityComparer(Func<TObject, TKey> keySelector)


public bool Equals(TObject x, TObject y) public bool Equals(TObject x, TObject y)
{ {
if (!typeof(TObject).IsValueType) {
// Reference semantics.
if (object.ReferenceEquals(x, y)) {
return true;
}

if (object.ReferenceEquals(x, default(TObject))) {
return object.ReferenceEquals(y, default(TObject));
}

if (object.ReferenceEquals(y, default(TObject))) {
return false;
}
}

return EqualityComparer<TKey>.Default.Equals(keySelector(x), keySelector(y)); return EqualityComparer<TKey>.Default.Equals(keySelector(x), keySelector(y));
} }


public int GetHashCode(TObject obj) public int GetHashCode(TObject obj)
{ {
if (!typeof(TObject).IsValueType) {
if (object.ReferenceEquals(obj, default(TObject))) {
throw new ArgumentNullException("obj");
}
}

return EqualityComparer<TKey>.Default.GetHashCode(keySelector(obj)); return EqualityComparer<TKey>.Default.GetHashCode(keySelector(obj));
} }


Expand Down

0 comments on commit e2576b6

Please sign in to comment.