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?
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.
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.
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 likeDictionary
class 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With