Wednesday, November 21, 2007

Reference variable in Applicate State

Most of us might think that when you save something to session, cache or other application state, ASP.NET save a copy of the variable to it. Take a cache for example, if you save a integer like this, we all know the cache value won't change

   1:  int i = 1;

   2:  Cache["Number"] = i;

   3:  i++;

   4:  //Cache["Number"] will still be 1



However, if you save a reference value, the cache object value changes as the reference object changes in the memory. like the exampel below the tc object in the cache is also changed when the tc in the memory changes. the Number property becomes 2.


private void TestCache()
{
TestClass tc;
if (Cache["TestClass"] != null)
tc = Cache["TestClass"] as TestClass;
else
{
tc = new TestClass();
Cache["TestClass"] = tc;
}
tc.Number = 2;
}

public class TestClass
{
public int Number = 0;
}


Another thing we should be aware of is: if you set the tc to null (tc=null), the object is still there in cache. This is because the tc=null state just breaks the reference of the tc and object allocated in the heap memory. so conside the following example, the Number property of the object in the cache is still 1 even if the tc.Number set to 2 later.



private void TestCache()
{
TestClass tc;
if (Cache["TestClass"] != null)
tc = Cache["TestClass"] as TestClass;
else
{
tc = new TestClass();
Cache["TestClass"] = tc;
}

tc = new TestClass();
tc.Number = 2;
}