title: How does this Singleton-like web class persists session data, even though session is not updated in the property setters?
body: <p>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.</p>
  
  <p>For example, if run this code on one page:</p>
  
  <pre><code>UserContext.Current.User.FirstName = "Micah";
  </code></pre>
  
  <p>And run this code in a different browser tab, FirstName is displayed correctly:</p>
  
  <pre><code>Response.Write(UserContext.Current.User.FirstName);
  </code></pre>
  
  <p>Can someone tell me (prove) how this data is getting persisted in the session?  Here is the class:</p>
  
  <pre><code>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; }
  }
  </code></pre>
  
  <p>I added this to a watch, and can see that the session variable is definitely being set somewhere:</p>
  
  <pre><code>(UserContext)System.Web.HttpContext.Current.Session["UserContext"];
  </code></pre>
  
  <p>As soon as a setter is called the Session var is immediately updated:</p>
  
  <pre><code>    set
      {
        HospitalField = value; //&lt;--- here
        ContractField = null;
        ModelType = null;
      }
  </code></pre>