Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to calculate hashcode from an object reference

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

like image 754
Wayne Avatar asked May 31 '10 16:05

Wayne


1 Answers

RuntimeHelpers.GetHashCode() does exactly what is needed here.

like image 121
Wayne Avatar answered Nov 06 '22 23:11

Wayne