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

I have a class A that implements IEquatable <>, using its fields (e.g. Ab and Ac) to implement / override Equals () and override GetHashCode (), and everything works fine, 99% of the time. Class A is part of the hierarchy (class B, C) that everyone inherits from interface D; they can be stored together in the Dictionary, so it’s convenient when they all carry their own Equals () / GetHashCode () by default.)

However, when building A, I sometimes need to do some work to get the values ​​for Ab and Ac; while this is happening, I want to keep a reference to the instance that is being built. In this case, I do not want to use the default overrides Equals () / GetHashCode () provided by A. So I was thinking of implementing ReferenceEqualityComparer, which was to force Object Equals () / GetHashCode () to be used.

    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 A) call Object.GetHashCode () on an instance of A?

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

thank

+3
2

object.ReferenceEquals RuntimeHelpers.GetHashCode.

. ObjectReferenceEqualityComparer<T>: IEqualityComparer<T>, ReferenceEquals

+7
-1

Source: https://habr.com/ru/post/1729704/


All Articles