How does this Singleton-like web class persists session data, even though session is not updated in
- by Micah Burnett
Ok, I've got this singleton-like web class which uses session to maintain state.  I initially thought I was going to have to manipulate the session variables on each "set" so that the new values were updated in the session.  However I tried using it as-is, and somehow, it remembers state.
For example, if run this code on one page:
UserContext.Current.User.FirstName = "Micah";
And run this code in a different browser tab, FirstName is displayed correctly:
Response.Write(UserContext.Current.User.FirstName);
Can someone tell me (prove) how this data is getting persisted in the session?  Here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class UserContext
{
  private UserContext() { }
  public static UserContext Current
  {
    get
    {
      if (System.Web.HttpContext.Current.Session["UserContext"] == null)
      {
        UserContext uc = new UserContext();
        uc.User = new User();
        System.Web.HttpContext.Current.Session["UserContext"] = uc;
      }
      return (UserContext)System.Web.HttpContext.Current.Session["UserContext"];
    }
  }
  private string HospitalField;
  public string Hospital
  {
    get { return HospitalField; }
    set
    {
      HospitalField = value;
      ContractField = null;
      ModelType = null;
    }
  }
  private string ContractField;
  public string Contract
  {
    get { return ContractField; }
    set
    {
      ContractField = value;
      ModelType = string.Empty;
    }
  }
  private string ModelTypeField;
  public string ModelType
  {
    get { return ModelTypeField; }
    set { ModelTypeField = value; }
  }
  private User UserField;
  public User User
  {
    get { return UserField; }
    set { UserField = value; }
  }
  public void DoSomething()
  {
  }
}
public class User
{
  public int UserId { get; set; }
  public string FirstName { get; set; }
}
I added this to a watch, and can see that the session variable is definitely being set somewhere:
(UserContext)System.Web.HttpContext.Current.Session["UserContext"];
As soon as a setter is called the Session var is immediately updated:
    set
    {
      HospitalField = value; //<--- here
      ContractField = null;
      ModelType = null;
    }