IEqualityComparer that uses ReferenceEquals

后端 未结 5 1997
野趣味
野趣味 2020-11-28 09:33

Is there a default IEqualityComparer implementation that uses ReferenceEquals?

EqualityComparer.Default uses

5条回答
  •  我在风中等你
    2020-11-28 10:17

    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
    {
        public static readonly ReferenceEqualityComparer Default
            = new ReferenceEqualityComparer(); // JIT-lazy is sufficiently lazy imo.
    
        private ReferenceEqualityComparer() { } // <-- A matter of opinion / style.
    
        public bool Equals(object x, object y)
        {
            return x == y; // This is reference equality! (See explanation below.)
        }
    
        public int GetHashCode(object obj)
        {
            return RuntimeHelpers.GetHashCode(obj);
        }
    }
    
    
    

    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.)

    提交回复
    热议问题