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?
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 likeDictionaryclass in C#.
They actually store the result in an IHttpSessionState object.
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.
Dictionary, if you try and Add to a dictionary twice with the same key, it will throw an exception. The indexer of a Dictionary works similarly to the Session object (it will either add or update, and will not throw an exception) - Matthew 2012-04-04 20:02