简体   繁体   中英

Store information using session variable

I'm new to ASP.NET :) and I'd like to understand more about session . Here's a simple example: Every time I click the button it will add one more integer to listInt and I store the list using Session["listInt"] .

public partial class TestSession : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["listInt"] == null)
            {
                Session["listInt"] = new List<Int16>();
            }
        }

    }

    protected void AddInt_Click(object sender, EventArgs e)
    {
        Int16 i = 0;
        List<Int16> listInt = (List<Int16>)Session["listInt"];
        listInt.Add(i);
        Session["listInt"] = listInt;
        Response.Write("Hello!");

    }
}

Here's the thing I don't understand, if I comment the line Session["listInt"] = listInt; , whenever I click the variable Session["listInt"] still store the value (means still add more integer to the list):

        Int16 i = 0;
        List<Int16> listInt = (List<Int16>)Session["listInt"];
        listInt.Add(i);
        //Session["listInt"] = listInt;  //No idea why....
        Response.Write("Hello!");

Can anyone please tell me how session works in this case? Thanks in advance :)

Your list is a reference type, so when you retrieve it from the server via the session state container you actually get a reference to some object in the server memory. Hence no need to reassign it later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM