Remove unused objects from the session
The Session in ASP.NET is a very simple way of storing user specific data for the duration of a single user session. I’ve many times added data to the Session that had an even shorter lifespan. That could be as a data store for properties on AJAX enabled web pages and those properties don’t belong in the session after the visitor navigates to another page on my website. To clean up, I would then delete those session objects that no longer is in use.
There are two way of deleting individual objects from the Session. You can set it to null or remove it.
Session[
"key"] = null;>or
Session.Remove(
"key");> >I used to think that the Session would treat the two ways the same, but that is not the case. If you set the object to null, the key still exists in the Session even though the value is null. This behaviour is the same as any other dictionary type classes in the CLR, but for some reason I thought that the Session was different.
That’s probably because you can ask if an key is present in the session without it throws an exception like many collection and dictionary type classes do if it isn't. It's because the Session is based on a HashTable. After .NET 2.0 with Generics was released, I haven't used a Hashtable one single time ever since. I always use the strongly typed generic collections and dictionary type classes instead, so that was probably what confused me.
Recap: If you want to remove an object completely from the Session, you should use the Session.Remove(“key”) method. It wont throw an exception if the key is not present in the Session.