HttpRuntime.Cache

  • Thread starter Thread starter Jose Fernandez
  • Start date Start date
J

Jose Fernandez

Hello
First of all, sorry for my bad english ;)

I have a USER class that i create to every user that enters the website (not
neccesarily logged in). At the same time i insert it into a the
HttpRuntime.Cache if it doesn't exist.
In every request i verify if the user is in the Cache so i don't have to
create it again. If it exists, i instantiate an USER object with the Cache
object already saved.
this is more or less the idea

string key="user"+RandomValue;
if(HttpRuntime.Cache[key]==null)
{
Usuario miUser=new Usuario(); // by default, i initialize all private
fields in the constructor.
HttpRuntime.Cache.Insert(key,miUser,null,DateTime.Now.AddHours(1),TimeSpan.Zero);
miUser=Http.Runtime.Cache[key];
}
else
{
Usuario miUser=Http.Runtime.Cache[key];
}

My question is. If i change one private field value of my instance of the
USER class, will it be changed at the Cache object too? I think it does
'cause i'm referencing that object, not creating a new one (in the else
statement).
Is this OK or WRONG?
What i want is to keep the user object to keep its values along the
application life.

Saludos
 
It's a fairly simple thing for you to try and find out on your own :)

But your assumption is correct. You are only storing a reference in the
cache, any updates to that reference (or references of the reference) will
be reflected.

On note...

If you do:

User user = GetUserFromCache();
user.FirstName = "New Name";

you'll have updated it in the cache...if the object gets dropped from the
cache however, and you retrieve the user:

User user =GetUserFromCache(); the firstName will go back to what it was
before, because it was never persistend to a store, such as a database..

Karl
 
Back
Top