ASP.NET removing an item from Session?

David Basarab picture David Basarab · Nov 4, 2008 · Viewed 56.3k times · Source

Which method is preferred?

Session.Remove("foo");

Session["foo"] = null;

Is there a difference?

Answer

Buu Nguyen picture Buu Nguyen · Nov 4, 2008

Is there a difference?

There is. Session.Remove(key) deletes the entry (both key & value) from the dictionary while Session[key] = null assigns a value (which happens to be null) to a key. After the former call, the key won't appear in the Session#Keys collection. But after the latter, the key can still be found in the key collection.