1

My web application is caching a List of objects to avoid having to fetch them from a database over and over. On one page, the List is fetched from the cache and then additional objects added to the list and displayed in a data bound control. These additional objects are not meant to be cached, but still are somehow.

When you use the Cache.Get() method, is it supposed to return an object reference or a copy of that object?

Zachary
  • 143
  • 1
  • 8

2 Answers2

5

System.Web.Caching.Cache is a in-memory cache. That means the the object references are what are returned from a Cache.Get() call. When you modify the reference after you do a get you are modifing the same object that is still in the cache.

You will need to manually do a clone operation to not modify the original object.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • 1
    @CodeCaster I re-worded it to say "in-memory" cache instead of just "memory cache". I would not call Memcached "in-memory" due to it's out of process nature, however for most implementations of in-memory caches they do just store references unless they require all objects in the cache to be serializeable (which is a good sign that they do not just store references). – Scott Chamberlain Jul 27 '17 at 22:26
  • Thank you for your answer! I thought as much but wasn't sure. I've been used to using the Session variable for tasks like this previously. – Zachary Aug 04 '17 at 22:25
4

MSDN: Caching Application Data:

The Cache object has no information about the content of the items it contains. It merely holds a reference to those objects.

If you want to modify a list without altering its cached representation, simply create a new list using the original list as source:

var fromCache = Cache.Get("MyList") as List<Foo>;
if (fromCache != null)
{
    var listToModify = new List<Foo>(fromCache);
    listToModifyAdd(new Foo { ... });
}

Do note that this merely prevents the cached list from being modified, modifications to objects in the list will still represent from successive Cache.Get() calls.

If you want to prevent that as well, look at Deep cloning objects.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272