Welcome to ASP .NET tutorial, in this article we will learn the Difference between Session.Add("key",value) and Session["key"] = value.
Both Session.Add("key", value) and Session["key"] = value are used to add a key-value pair to a session object in ASP.NET or ASP.NET MVC(.Net Core as well).
However, there is a tiny difference between these two methods.
Session.Add("key", value) is a method call that adds the key-value pair to the session object. But it throws an exception, If the key already exists in the session.
On the other hand, Session["key"] = value is an index property that sets the value of the key in the session.
But it overwrites the existing value If the key already exists, else it adds If the key does not exist in the session.
Here's an example to illustrate the difference:
// Create a new session object Session["MySession"] = "SessionValue"; // Add a key-value pair to the session object Session.Add("MyAnotherSession", "SessionValueAnother"); // Try to add a key-value pair that already exists try { Session.Add("MySession", "newvalue1"); // Throws an exception } catch (Exception ex) { Console.WriteLine(ex.Message); } // Overwrite an existing value using the index property Session["MyAnotherSession"] = "newvalue1";
In this example, Session.Add("key1", "newvalue1") throws an exception because the key "key1" already exists in the session. However, Session["key1"] = "newvalue1" overwrites the existing value "value1" with "newvalue1".