Question

Time to learn some basics.

Look at the code below:

  protected void Button1_Click(object sender, EventArgs e)
 {

    List<string> a;
    if(Session["data"] == null)
    {
        a = new List<string>();
        a.Add("abc");
        a.Add("def");
        a.Add("ghi");

        Session["data"] = a;
    }
    else
    {
        a = (Session["data"] as List<string>);
    }
    a.Add("jkl");
    foreach (string s in a)
    {
        lblTest.Text += s + "<br />";
    }
}

There is nowhere else in the codebehind where I am doing anything with sessions. The expected behaviour of this code is that in the first run(click) session will hold a reference to "a". But "a" has local scope in the above function, so somewhere the value of "a" must be copied into the session. Where does that happen? Does it happen before the function gets executed because anywhere else that happens(i.e Page unload, validate, render) the List "a" will not be available. So when and where does the value assigned or referenced gets stored in the session?

Was it helpful?

Solution

a is a reference to your instance of List<string>. When you assign Session["data"] = a, it now also has a reference to that same instance of List<string>. So despite the fact that a goes out of scope, that list instance remains since at least one reference remains. Accessing Session["data"] will continue to return a reference to that same instance until it is removed from the session (or replaced by something else).

OTHER TIPS

So when and where does the value assigned or referenced gets stored in the session?

Here:

Session["data"] = a;

In the second run you are retrieving a from the session and adding an element to it. But since List<string> is a reference type, both a and Session["data"] are now pointing to the same location in memory so when you add an element to a you are basically modifying Session["data"] so you don't need to call Session["data"] = a once again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top