Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 'Session.Remove(key)' v/s 'Session(key) = nothing'

I've seen developers use two approaches when they are done with a session object.

1) Session.Remove(key)

2) Session(key) = nothing

What is the better approach of the two above? Does Session.Remove dispose the object stored automatically?

Does the second approach depend on the garbage collector to actually free up the memory?

EDIT: Thanks for the responses, guys. Seems like Session.Remove is the correct way to go. However, if Session.Remove does not guarantee the disposal of object, then what is the best way to dispose the object stored in session when we do not need it further?

Thanks.

like image 243
Srikanth Venugopalan Avatar asked Jun 02 '10 14:06

Srikanth Venugopalan


People also ask

How do you remove a session?

Destroying a PHP Session A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

How do I check if a session key exists?

Answers. Morover put a breakpoint in the session and check the exact value of session after clearing.

How do you make a session null?

You can set session variables in usual way using string as a key e.g. Session["Key"] = obj; To destroy the object in Session set it to null. Session["Key"] = null. you can clear the user session through the session.

How can delete session in ASP NET MVC?

Another way as you said is to use Session. Clear() method. But the best way is to set another irrelevant object (usually null value) in the session in correspondance to a key. For example, to nullify Session["FirstName"] , simply set it to Session["FirstName"] = null .


1 Answers

If you set the object to null or nothing, 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.

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.

like image 112
Ed B Avatar answered Oct 04 '22 01:10

Ed B