Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 491
Jimmy Avatar asked Jan 23 '10 16:01

Jimmy


1 Answers

The natural match for object.ReferenceEquals is RuntimeHelpers.GetHashCode.

See the answer to this question for full details and an implementation of ObjectReferenceEqualityComparer<T>: Built-in IEqualityComparer<T> that uses ReferenceEquals

like image 172
Sam Harwell Avatar answered Nov 14 '22 21:11

Sam Harwell