I need to generate a unique hash code for an object, based on its contents, e.g. DateTime(2011,06,04) should equal DateTime(2011,06,04).
- I cannot use .GetHashCode() because it might generate the same hash code for objects with different contents.
- I cannot use .GetID from ObjectIDGenerator as it generates a different hash code for objects with the same contents.
- If the object contains other sub-objects, it needs to recursively check these.
- It needs to work on collections.
The reason I need to write this? I’m writing a caching layer using PostSharp.
Update
I think I may have been asking the wrong question. As Jon Skeet pointed out, to be on the safe side, I need as many unique combinations in the cache key as there are combinations of potential data in the object. Therefore, the best solution might be to build up a long string that encodes the public properties for the object, using reflection. The objects are not too large so this is very quick and efficient:
- Its efficient to construct the cache key (just convert the public properties of the object into a big string).
- Its efficient to check for a cache hit (compare two strings).
If you need to create a unique hash code, then you’re basically talking about a number which can represent as many states as your type can have. For
DateTimethan means taking the Ticks value and theDateTimeKind, I believe.You may be able to get away with assuming that the top two bits of the
Ticksproperty are going to be zero, and using those to store the kind. That means you’re okay up until the year 7307 as far as I can tell: