Reputation: 21
if I put a custom class in session, then in an action method I get an instance of that class from session, and populate some fields, I noticed that when a different controller gets that class from session, those fields are populated. Even though after the first call didn't save the updated class back in session.
is this typical behavior for session objects?
I thought I had to use keyword 'static' on the class in session for this to happen
thanks
Upvotes: 2
Views: 947
Reputation: 1038780
As your class is a reference type this is the normal behavior. Here's what's happening in memory:
You instantiate an object and put it in session
var someObj = new SomeObject();
Session["someObj"] = someObj;
At this stage a new object is created on the heap and Session["someObj"]
is pointing to this object.
You retrieve the object from session in controller A and modify some property but you do not call Save
:
var someObj = (SomeObject)Session["someObj"];
someObj.SomeProp = "new value";
Now someObj
is pointing to this same object you created earlier on the heap. As someObj
is only a reference you are actually modifying the original object in memory.
You retrieve the object from session in Controller B:
var someObj = (SomeObject)Session["someObj"];
Now someObj
points to the same memory location which has been modified.
Upvotes: 6
Reputation: 44322
Since your session is in memory this is the expected behavior. If you store the session in an external store then you have to save the objects back to the session to get that same behvior. I would try to avoid such development becuase when you do change the store the behavior is totally different.
Upvotes: 0
Reputation: 20842
is this typical behavior for session objects?
Well yes, but, it is typical of .NET objects in general. You took a reference, so you were changing the original object still pointed to by the session.
Upvotes: 1