Why does Cache.Add return an object that represents the cached item?
asp.net, caching
Solution
Calling Add() on a cache eventually calls an internal method with this signature:
internal abstract CacheEntry UpdateCache(CacheKey cacheKey,
CacheEntry newEntry, bool replace, CacheItemRemovedReason removedReason,
out object valueOld);
Notice the `out object valueOld` - this gets set to the object that is currently in the "cacheKey" location in the cache, and is returned as the result of Add(). The documentation is misleading, it's not actually the same object that is returned - it's whatever object was at that same key location.
This is easily verified with the following code:
String x = "lorem";
String y = "ipsum";
HttpContext.Current.Cache.Add("hi", x, null, DateTime.MaxValue,
Cache.NoSlidingExpiration,
CacheItemPriority.Normal, null);
var z = HttpContext.Current.Cache.Add("hi", y, null, DateTime.MaxValue,
Cache.NoSlidingExpiration,
CacheItemPriority.Normal, null);
//Result:
// z == "lorem"
Problem
From MSDN about the differences between Adding or Inserting an item the ASP.NET Cache: Note: The Add and Insert methods have the same signature, but there are subtle differences between them. First, calling the Add method returns an object that represents the cached item, while calling Insert does not. Second, their behavior is different if you call these methods and add an item to the Cache that is already stored there. The Insert method replaces the item, while the Add method fails. [emphasis mine] The second part is easy. No question about that. But with the first part, why would it want to return an object that represents the cached item? If I'm trying to Add an item to the cache, I already have/know what that item is? I don't get it. What is the reasoning behind this?