C# how to calculate hashcode from an object reference.
Posted
by Wayne
on Stack Overflow
See other posts from Stack Overflow
or by Wayne
Published on 2010-05-31T16:28:30Z
Indexed on
2010/05/31
16:33 UTC
Read the original article
Hit count: 285
Folks, here's a thorny problem for you!
A part of the TickZoom system must collect instances of every type of object into a Dictionary<> type.
It is imperative that their equality and hash code be based on the instance of the object which means reference equality instead of value equality. The challenge is that some of the objects in the system have overridden Equals() and GetHashCode() for use as value equality and their internal values will change over time. That means that their Equals and GetHashCode are useless. How to solve this generically rather than intrusively?
So far, We created a struct to wrap each object called ObjectHandle for hashing into the Dictionary. As you see below we implemented Equals() but the problem of how to calculate a hash code remains.
public struct ObjectHandle : IEquatable<ObjectHandle>{
public object Object;
public bool Equals(ObjectHandle other) {
return object.ReferenceEquals(this.Object,other.Object);
}
}
See? There is the method object.ReferenceEquals() which will compare reference equality without regard for any overridden Equals() implementation in the object.
Now, how to calculate a matching GetHashCode() by only considering the reference without concern for any overridden GetHashCode() method?
Ahh, I hope this give you an interesting puzzle. We're stuck over here.
Sincerely, Wayne
© Stack Overflow or respective owner