user203687
user203687

Reputation: 7247

Can I modify ASP.NET session object this way?

Imagine that I have an instance (oEmp) of "Employee" class and I would like to store it session.

Session["CurrentEmp"] = oEmp;

If I modify a property in oEmp as follows:

oEmp.Ename = "Scott";

Am I referring to session item through above statement or just only "oEmp"?

Session["CurrentEmp"] = oEmp; //Do we still need this after any property is modified

Is that the same case, if I opted for SQL Server session state (instead of InProc).

thanks

Upvotes: 4

Views: 1650

Answers (3)

Amit Rai Sharma
Amit Rai Sharma

Reputation: 4225

I am updating my response as my understanding of session data serialisation was not correct. I am not going to delete this answer as it might help other understand how session works. I would thank @Guru for point this out.

Irrespective of session mode, session data is updated back to session object only when the request is successful. So if you have assigned a reference object to session and then update the object in the same request, the session will hold the updated information.

Refer: Underpinnings of the Session State Implementation in ASP.NET for more information

Upvotes: 2

Guru Kara
Guru Kara

Reputation: 6462

Session Variables are held as reference types so there is no need to update its value every time.
You object instance that you store, only the reference to that object is stored in the session variable.

Here are some link to help you find more details

http://bytes.com/topic/asp-net/answers/447055-reference-types-session

http://forums.asp.net/t/350036.aspx/1

Do asp.net application variables pass by reference or value?

Upvotes: 2

Joe Ratzer
Joe Ratzer

Reputation: 18549

Asp.net Session will hold the reference, so you shouldn't need to do the following:

Session["CurrentEmp"] = oEmp;

after modifying oEmp;

Upvotes: 7

Related Questions