Session and Cache are By Reference

Recently a colleague remarked that if he got a List of some type out of the ASP.NET Cache, and changed an item, the Cache item would also change.

That is correct. Session (InProc) , Cache and Application all return "live" references. A good writeup on this can be found by friend and fellow MVP Rick Strahl here:
http://www.west-wind.com/Weblog/posts/1214.aspx

If you do not want this behavior, you need to either delete the Session / Cache / Application object and replace it with what you want later, or store a clone by duplicating the object, doing your work on the original that you got out of Cache, then replacing the existing cached item with your clone that was not changed.

for example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CachebyRef
{
public class Person
{
public String FirstName { get; set; }
public String LastName { get; set; }
}

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List list = new List();
list.Add(new Person(){FirstName="Joe",LastName = "Blow"});
Cache["personList"] = list;
List newList = (List) Cache["personList"];
Person p = newList[0];
Response.Write(p.FirstName + ": " + p.LastName + "<br/>");
p.FirstName = "Altered";
p.LastName = "State";
List altList = (List) Cache["personList"];
Person q = altList[0];
// Surprise - the cached item contains the change:
Response.Write(q.FirstName + ": " + q.LastName);
}
}
}

Comments

  1. Nicolas2:14 PM

    I'm studying the C# language in Argentina and I'm wondering if you can tell me which book you recommend to learn more about this great language. thank you very much

    ReplyDelete
  2. @Nicolas,
    That would be hard as there are so many good books. When you get past the beginner stage, though, I'd recommend "C# 4.0 In a Nutshell" by the Albahari brothers (O'Reilly)

    ReplyDelete
  3. Anonymous1:19 PM

    Hi Peter,

    In silverlight applications, all the collection classes are mostly of reference type. Even a list.clone will produce a referenced set. if you change the data in cloned list, the actual list get updated. I am not sure why Microsoft did like this

    ReplyDelete

Post a Comment

Popular posts from this blog

Some observations on Script Callbacks, "AJAX", "ATLAS" "AHAB" and where it's all going.

IE7 - Vista: "Internet Explorer has stopped Working"

FIREFOX / IE Word-Wrap, Word-Break, TABLES FIX