Asp.net – Do changes to session objects persist?

I’m using the session to hold a custom object UserSession and I access the session like this:

UserSession TheSession = HttpContext.Current.Session["UserSession"] as UserSession;

Then, in my code, I modify a property of TheSession like this

TheSession.Prop1 = some new value;

My question is this: when I change the value, does it change the value inside the session that’s in HttpContext.Current.Session[“UserSession”] or just the TheSession variable, in which case I’d need to reassign the object variable to the session.

Thanks.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The standard session provider is a simple dictionary that stores objects in memory.

You’re modifying the same object that you put in the session, so the modifications will persist.
(unless you’re using an evil mutable struct)

Method 2

Yes it is the same object. It is very easy to see in the following example:

Session["YourObject"] = yourObject;
yourObject.SomeProperty = "Test";
var objectFromSession = (YourObjectType)(Session["YourObject"]);
Response.Write(objectFromSession.SomeProperty);

The Write will display: Test

Method 3

create a static class with static properties:

public static class UserSession
{
    public static int UserID
    {
         get { return Convert.ToInt32(Session["userID"]); }
         set { Session["userID"] = value; }
    }
}

When u use it:

UserSession.UserID = 23;
Response.Write(UserSession.UserID);

it will use the session variable to store information passed to this property.

Method 4

It doesn’t need to reassign the object. Because both of them are pointing to same instance in memory


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x