tags:

views:

40

answers:

3

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 ?????
    }
}
+2  A: 

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

Andrey
Yes, but I need access to that functionality in another way.
erikkallen
@erikkallen In what other way?
Martin Harris
@Andrey: 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
@Fredrik Mörk that's true. i wanted to point to that default implementation will return different hash codes for memberwise equal objects.
Andrey
+1  A: 

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.

Martin Harris
+2  A: 

You are probably looking for RuntimeHelpers.GetHashCode

Hemal Pandya
it is complete equivalent for object.GetHashCode
Andrey
Thank you, that's it.
erikkallen
@Andrey it is equivalent only if the dynamic type of object does not override GetHashCode. @erikkallen you are welcome.
Hemal Pandya