views:

23

answers:

2

At a lot of places I have seen the following pattern. Consider the code:

Customer cust = (Customer) Session["Customer"]; 

//Do something to the object cust

Session["Customer"] = cust

and the code :

Customer cust = (Customer) Cache["Customer"];

//do something to object cust
Cache["Customer"] = cust;

Now, in the second case, putting the cust object back to Cache is not required as the reference is the same and any changes to the cust object shall be reflected in the cache.

But I dont think that is the case in case of Session, where the cust object has to be explicitly put back into the Session. However, I am not sure. Will the change reflect in Session if I do not explicitly specify the change as above?

And if it needs to be done explicitly, why the difference in behavior with Cache object? Both places we seem to be doing a reference passing.

This is for C#, ASP.NET

A: 

You do not have to explicitly reassign the object back to the Session. Any changes made on an object retrieved from Session will be reflected and persisted within the Session. Cache is different because it may expire. If you need any further assistance, let me know.

One other thing, InProc Session is faster than Cache because Cache has to check expirations before returning the object.

The object stored in Session and in Cache is just a pointer to the object, so any changes made to the object will be persisted WITHOUT the need to explicitly reassign the object back to the Session or Cache it came from.

Breakskater
Unless it is an immutable type, such as a string.
Nikki9696
+2  A: 

Strings are immutable. Why worry about a data type and whether or not you need to reassign it? Just reassign it to be safe and clear about your intentions.

To see what I mean, run this and check the values. You will see it did NOT change in the session. The value of x will be "bar".

        Session["foo"] = "bar";

        var s = Session["foo"];
        s = "baz";

        var x = Session["foo"];

        Debugger.Break();
Nikki9696