nlips
nlips

Reputation: 1288

stable hashcode for IStructuralEquatable object

I need to build a stable (= does not vary with time) hashcode of an object. Specifically, I do not know the exact type of the object. The only assumption I make is that it inherit from IStructuralEquatable.

So I need a method:

static string GetStableHashcode <T> (T object) where T: IStructuralEquatable

The .Net framework provide this type of function? Otherwise, which algorithm to use?

Upvotes: 0

Views: 188

Answers (2)

Martin Liversage
Martin Liversage

Reputation: 106926

There is no need to use generics in your function so your question is how to implement the method

static string GetStableHashcode(IStructuralEquatable obj) { ... }

And the only sensible solution is to implement it like this:

static string GetStableHashcode(IStructuralEquatable obj) {
  return obj.GetHashCode().ToString();
}

Your concern is that Object.GetHashCode() does not provide values that are stable and the concern is very valid as can be seen in the first box headed by Caution in the documentation:

  • Do not serialize hash code values or store them in databases.

  • [...]

  • Do not send hash codes across application domains or processes. In some cases, hash codes may be computed on a per-process or per-application domain basis.

Actually, some hash codes created by Object.GetHashCode are stable like Int32.GetHashCode and String.GetHashCode and the algorithm used by Tuple.GetHashCode will also combine hash codes in a "stable manner". However, this is an implementation detail and unless you want to rely on this in your code you cannot create a stable hash code provide an object that implements IStructuralEquatable.

Upvotes: 0

Wilbert
Wilbert

Reputation: 7419

Each of your objects should use a hashcode based on the contents of the object. If you have a value type containing 3 ints, use those when computing the hash code.

Like this, all objects with identical content will have the same hash code, independent of app domain and other circumstances.

An example for a good hash code can be found in this answer.

Upvotes: 0

Related Questions