The following is how I usually handle objects in Session State, I have a const string as the session name and then have a property with a get and set for the Object.
What I was wondering was if the 'Session.Remove()' call was necessary (to keep things clean and tidy) and if there was significant overhead and doing this removal.
I have the Session.Remove there basically because it makes me feel better (OCD i know), and makes me feel like the session is cleaner, but I would like to know if it isn't needed.
private const string sesMyObject = "{C2CC72C3-1466-42D4-8579-CAA11F261D55}";
public MyObject MyObjectProperty
{
get
{
return Session[sesMyObject] as MyObject;
}
set
{
Session.Remove(sesMyObject);
Session.Add(sesMyObject, value);
}
}
EDIT per the answers below i have changed my properties to the following:
private const string sesMyObject = "{C2CC72C3-1466-42D4-8579-CAA11F261D55}";
public MyObject MyObjectProperty
{
get
{
return Session[sesMyObject] as MyObject;
}
set
{
Session[sesMyObject] = value;
}
}
thanks!
If you really want to be safe, try converting the object to a IDisposable, and if it succeeds, call Dispose.
IDisposable sesDispObj = Session[sesMyObject] as IDisposable;
if (sesDispObj != null)
sesDispObj.Dispose();
Other than that,
Session[sesMyObject] = value
is pretty much the same as
Session.Remove(sesMyObject);
Session.Add(sesMyObject, value);
It's overkill. Refering MSDN
If the name parameter refers to an existing session state item, the existing item is overwritten with the specified value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With