Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using session to get/set object properties everytime

I tried searching for this but I'm not even sure how to phrase it for the search.

What I'm attempting to do is have a class that everytime I access it to change it, I'm really getting and setting the value from session.

Here's what I'm trying to do (what I have so far.):

public class example
{
   public int prop1 {get;set;}

   public static example Instance
   {
       return (example)(HttpContext.Current.Session["exampleClass"] ?? new example());
   }

}

public class main
{
   protected void Page_Load(object sender, EventArgs e)
   {
      example.Instance.prop1 = "aaa"; //stores value into session
      txtInput.Text = example.Instance.prop1; //retrieves value from session
   }
}

I hope that makes sense on what I am trying to do.

Any help would be appreciated, thank you.

like image 260
JMD Avatar asked Dec 01 '22 00:12

JMD


1 Answers

This would be easy to do with generics.

Give this a try.

public class Session
{
    public User User
    {
        get { return Get<User>("User"); }
        set {Set<User>("User", value);}
    }

    /// <summary> Gets. </summary>
    /// <typeparam name="T"> Generic type parameter. </typeparam>
    /// <param name="key"> The key. </param>
    /// <returns> . </returns>
    private T Get<T>(string key)
    {
        object o = HttpContext.Current.Session[key];
        if(o is T)
        {
            return (T) o;
        }

        return default(T);
    }

    /// <summary> Sets. </summary>
    /// <typeparam name="T"> Generic type parameter. </typeparam>
    /// <param name="key">  The key. </param>
    /// <param name="item"> The item. </param>
    private void Set<T>(string key, T item)
    {
        HttpContext.Current.Session[key] = item;
    }
}
like image 178
Chuck Conway Avatar answered Dec 04 '22 23:12

Chuck Conway