shenku
shenku

Reputation: 12420

Can I use the hashcode of an object as a cache key?

can I use the hashcode of an object as a cachekey?

My assumption is that the hash would be the same for each Criteria, where the property values are the same?

Something like this:

function void Method1(Criteria criteria)
{ 
        ObjectCache cache = MemoryCache.Default;
        string CacheKey = "Method1-" + criteria.GetHashCode();

        if(cache.Contains(CacheKey))
            return (IEnumerable)cache.Get(CacheKey);
        else
        {
            IEnumerable stuff = repository.GetStuff();
 
            CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
            cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1.0);
            cache.Add(CacheKey, stuff, cacheItemPolicy);
 
            return stuff;
        }
}

Upvotes: 3

Views: 1953

Answers (2)

Jon
Jon

Reputation: 437326

can I use the hashcode of an object as a cachekey?

No. Not without an additional failsafe.

My assumption is that the hash would be the same for each Criteria, where the property values are the same?

The assumption is wrong. Hash codes are required to be the same only for objects that implement IEquatable<T> and are equal, but even in that case they are not required to be different for objects that are unequal. Since in the general case the number of possible different Criteria instances is infinite while the range of the hash code is finite, there will always be collisions due to the pigeonhole principle.

Upvotes: 4

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

Yes, GetHashCode implemented right returns the same int value for the same object state (e.g. the same properties values). However, you can't assume that every object with different state/values will have different hash code. It's possible to have the same hash code for different objects, even when GetHashCode is implemented right.

Upvotes: 2

Related Questions