views:

1294

answers:

6

Which method is preferred?

Session.Remove("foo");

Session["foo"] = null;

Is there a difference?

A: 

it's the same..

Arief Iman Santoso
+6  A: 

I would go with Remove but can not honestly say if there is a difference. At a guess there may still be an empty key kept for that null value but not sure. Remove would give me little doubt and if that's what you want to do it reads better in code as well.

dove
A: 

Perhaps it's the same as Arief says. But I prefer Session.Remove since it's more legible.

ullmark
+5  A: 

It has the same effect. I personally think, the Session.Remove method does better express the programmer's intent.

Here some links to the documentation on MSDN:

"HttpSessionState.Item Property:

Property Value Type: System.Object

The session-state value with the specified name, or null reference (Nothing in Visual Basic) if the item does not exist."

splattne
+6  A: 

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.

Buu Nguyen
+3  A: 

The biggest difference is how you read from session.

if(Session.ContainsKey["foo"]) { return Session["foo"]; }

or

if(Session["foo"] != null) { return Session["foo"]; }

If you use the first method, setting the value to null will not work, and you should use remove.

If you use the second method, you can set the value to null.

FlySwat