2

How can I generate a hash code for an object based on its identity.

What I mean is that:

  • if object.ReferenceEquals(a, b) == true, then a and b will get the same hash code.
  • if object.ReferenceEquals(a, b) == false, then a and b should have a decent chance to get different hash codes even if they are memberwise equal.

What I have is:

class SomeClassThatMakesSenseToCompareByReferenceAndByValue {
    override Equals(object o) {
        return MemberwiseEquals(o);
    }

    override GetHashCode() {
        return MemberwiseGetHashCode();
    }
}

class SomeClassThatNeedsReferenceComparison {
    SomeClassThatMakesSenseToCompareByReferenceAndByValue obj;

    override Equals(object o) {
        return o is SomeClassThatNeedsReferenceComparison && object.ReferenceEquals(this.obj, (o as SomeClassThatNeedsReferenceComparison).obj);
    }

    override GetHashCode() {
        return ?????
    }
}
3
  • 2
    It may help to explain in a bit more detail your use cases for this. Commented Aug 23, 2010 at 11:15
  • "[...] get different hash codes even if they are memberwise equal" - that sounds a bit odd. Consider the following text from the GetHashCode documentation (under "Notes to implementers"): "If two objects compare as equal, the GetHashCode method for each object must return the same value". I may miss something though. Commented Aug 23, 2010 at 11:40
  • That's why my SomeClassThatMakesSenseToCompareByReferenceAndByValue class returns a consistent hash code. But in my other class, I want to use GetHashCode AND Equals based on identity. Commented Aug 23, 2010 at 12:01

3 Answers 3

3

You are probably looking for RuntimeHelpers.GetHashCode

Sign up to request clarification or add additional context in comments.

2 Comments

it is complete equivalent for object.GetHashCode
@Andrey it is equivalent only if the dynamic type of object does not override GetHashCode. @erikkallen you are welcome.
2

if you don't override GetHashCode it will return that identic hash code.

4 Comments

Yes, but I need access to that functionality in another way.
@erikkallen In what other way?
given that object.ReferenceEquals(a, b) == true I would say that hardly any implementation of GetHashCode would yield a different result for a and b (it would basically require involving random elements or time).
@Fredrik Mörk that's true. i wanted to point to that default implementation will return different hash codes for memberwise equal objects.
1

Don't do anything - since both objects point to the same instance the same HashCode will always be generated for both objects using the default implementation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.