Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Difference between Session.Add("key",value) and Session["key"] = value?

Can somebody please explain to me the difference between:

Session.Add("name",txtName.text); and Session["name"] = txtName.text;

It was an interview question and I answered that both store data in key = "Value" format like Dictionary class in C#.

Am I right, or is there any difference?

like image 424
Chandan Kumar Avatar asked Apr 04 '12 19:04

Chandan Kumar


People also ask

Where is session key stored?

1 Answer 1. Browsers will store the session keys in memory. They won't be retrievable in any XSS attack because they are not stored in the DOM.

What is session in C# with example?

Session is a State Management Technique. A Session can store the value on the Server. It can support any type of object to be stored along with our own custom objects. A session is one of the best techniques for State Management because it stores the data as client-based.


2 Answers

Looking at the code for HttpSessionState shows us that they are in fact the same.

public sealed class HttpSessionState : ICollection, IEnumerable {     private IHttpSessionState _container; ...     public void Add(string name, object value)     {         this._container[name] = value;     }      public object this[string name]     {         get         {             return this._container[name];         }         set         {             this._container[name] = value;         }     } ... } 

As for them both

Storing data in key = "Value" format like Dictionary class in C#.

They actually store the result in an IHttpSessionState object.

like image 176
Sean Kearney Avatar answered Oct 16 '22 06:10

Sean Kearney


The two code snippets you posted are one and the same in functionality. Both update (or create if it doesn't exist) a certain Session object defined by the key.

Session.Add("name",txtName.text);

is the same as:

Session["name"] = txtName.text;

The first is method-based, where the second is string indexer-based.

Both overwrite the previous value held by the key.

like image 35
KP. Avatar answered Oct 16 '22 07:10

KP.