Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing and retrieving multiple values in a single session

I know there are topics with similar heading, but this is kinda different.

First, in order to store multiple values in a single session, I have to use a List whereas I store the list with the values in the session, right ?

If so, when I want to add a value to the List, which is already in the session, then I retrieve the List from the session and add the value. But do I need to assign the List back to the session every time I have added/removed a value from the List? Or ,by default, it gets automatically updated in the session when I manipulate it as it was assigned at first in the session and after that.

UPDATE: providing sample code of my question

public void assignNewID(int currentID)
{
    if(Session["usersID"] == null)
    {
        Session["usersID"] = new List<int>();
    }

    if(currentID != null)
    {
        var list = (List<int>)Session["usersID"];
        list.Add(currentID);

        // now should I hereby assign the list back to
        // the session like:
        // Session["usersID"] = list;
        // or it gets automatically updated in the session by default ?
    }
}
like image 839
Syspect Avatar asked Dec 06 '25 03:12

Syspect


1 Answers

List is a reference type so you are storing a reference to your session which will be updated if the object gets updated ,

Session gets updated for reference type

like image 197
Suraj Singh Avatar answered Dec 08 '25 18:12

Suraj Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!