C# – ASP.NET removing an item from Session

.netasp.netc++sessionsession-variables

Which method is preferred?

Session.Remove("foo");

Session["foo"] = null;

Is there a difference?

Best Solution

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.