Reputation: 4387
I currently have the following code:
public MyObject SessionStore
{
get
{
if (Session["MyData"] == null)
Session["MyData"] = new MyObject();
return (MyData) Session["MyData"];
}
set
{
Session["MyData"] = (MyObject) value;
}
}
I access it using SessionStore.ThePropertyIWant
I set it using SessionStore = SessionStore
This works; but is there a better way of accomplishing the same thing?
Upvotes: 1
Views: 6327
Reputation: 18013
SessionStore is fine but you could end up with alot of properties. I tend to add protected properties to base bases and access from there.
eg:
/// <summary>
/// Gets or Sets the Current Order Line
/// </summary>
protected OrderLine CurrentOrderLine
{
get
{
if (Session["CurrentOrderLine"] == null)
{
Session["CurrentOrderLine"] = new OrderLine(this.CurrentOrder);
}
return Session["CurrentOrderLine"] as OrderLine;
}
set
{
Session["CurrentOrderLine"] = value;
}
}
then it would appear as a property on your page if you inheriet from it.
Upvotes: 1
Reputation: 31192
You don't need to cast in the setter, and can make the getter more concise :
public MyData SessionStore
{
get { return (MyData)(Session["MyData"]) ?? new MyData(); }
set { Session["MyData"] = value; }
}
Upvotes: 1