question about session

clemtuf

Member
Joined
Jan 7, 2023
Messages
5
Programming Experience
3-5
Hi,
this code works perfect (without the last line!). The elements of list<T> are retained by the Session variable after each postback. But i'm wondering how it can work without the last line: Session["time"] = time;. When a new element is added to the list, if Session["time"] is not present, then it's not updated and doesn't contain the new element. According to me, the line time = (List<int>)Session["time"]; can't contain anyyhing.
Any explanation for this: why is that line Session["time"] = time; not necessary?
Thanks

C#:
using System;
using System.Collections.Generic;
    public partial class WebForm : System.Web.UI.Page
    {
        List<int> time = new List<int>();
        protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Focus();
            if (!Page.IsPostBack)
            {
                Session["time"] = time; // empty
            }
        }
        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            Label1.Text = "";
            time = (List<int>)Session["time"];
            time.Add(Convert.ToInt32(TextBox1.Text));
            time.Sort();
            for (int i=0;i< time.Count;i++)
            Label1.Text += time[i].ToString() + " ";
            TextBox1.Text = "";
//Session["time"] = time; // works without this line
        }
    }
 
Last edited by a moderator:
The reason why it works is because of object references. Line 11 puts a reference to the list on line 11. On line 17, you are simply referring back to the same reference that you put into the session.

Be aware that this will generally only work when you are using in-proc session state. So the reference in the session state just points to the same block of memory.

When you move to a web farm where you have multiple machines and you start using a SQL server or Redis for your session state, the objects you put into the session state will have to serialized and deserialized. In that case, you will likely need that last line to force a serialization of the state on one web frontend to get shared with the other web front ends.
 

Latest posts

Back
Top Bottom