How to use Object.GetHashCode() on a type that overrides GetHashCode()

Posted by Jimmy on Stack Overflow See other posts from Stack Overflow or by Jimmy
Published on 2010-01-23T16:56:39Z Indexed on 2010/03/29 3:23 UTC
Read the original article Hit count: 463

Hi,

I have a class A that implements IEquatable<>, using its fields (say, A.b and A.c) for implementing/overriding Equals() and overriding GetHashCode(), and everything works fine, 99% of the time. Class A is part of a hierarchy (class B, C) that all inherit from interface D; they can all be stored together in a dictionary Dictionary, thus it's convenient when they all carry their own default Equals()/GetHashCode().

However, while constructing A I sometime need to do some work to get the values for A.b and A.c; while that's happening, I want to store a reference to the instance that's being built. In that case, I don't want to use the default Equals()/GetHashCode() overrides provided by A. Thus, I was thinking of implementing a ReferenceEqualityComparer, that's meant to force the use of Object's Equals()/GetHashCode():

    private class ReferenceEqualityComparer<T> : IEqualityComparer<T>
    {
        #region IEqualityComparer<T> Members
        public bool Equals(T x, T y)
        {
            return System.Object.ReferenceEquals(x, y);
        }

        public int GetHashCode(T obj)
        {
            // what goes here? I want to do something like System.Object.GetHashCode(obj);
        }
        #endregion
    }

The question is, since A overrides Object.GetHashCode(), how can I (outside of A) call Object.GetHashCode() for an instance of A?

One way of course would be for A to not implement IEquatable<> and always supply an IEqualityComparer<> to any dictionary that I create, but I'm hoping for a different answer.

Thanks

© Stack Overflow or respective owner

Related posts about gethashcode

Related posts about iequalitycomparer