Is there a default IEqualityComparer implementation that uses ReferenceEquals?
EqualityComparer uses
I thought it was time to update the previous answers implementation to .Net4.0+ where it simplifies by becoming non-generic thanks to contravariance on the IEqualityComparer interface:
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public sealed class ReferenceEqualityComparer
: IEqualityComparer, IEqualityComparer
Now there only needs to exist one instance for all your reference-equality checking instead of one for each type T as was the case before.
Also you save typing by not having to specify T every time you want to use this!
To clarify for those who are not familiar with the concepts of Covariance and Contravariance...
class MyClass
{
ISet setOfMyClass = new HashSet(ReferenceEqualityComparer.Default);
}
...will work just fine. This is not limited to e.g. HashSet or similar (in .Net4.0).
Also for anyone wondering why x == y is reference equality, it is because the ==operator is a static method, which means it is resolved at compile-time, and at compile-time x and y are of type object so here it resolves to the ==operator of object - which is the real reference equality method. (In fact the Object.ReferenceEquals(object, object) method is simply a redirect to the object equals operator.)