views:

2020

answers:

3

is it possible to store list to session variable in Asp.net C# ?

+6  A: 

Yes, you can store any object (I assume you are using ASP.NET with default settings, which is in-process session state):

Session["test"] = myList;

You should cast it back to the original type for use:

var list = (List<int>)Session["test"];
// list.Add(something);

As Richard points out, you should take extra care if you are using other session state modes (e.g. SQL Server) that require objects to be serializable.

Mehrdad Afshari
Not exactly true. If you need to use a different session store than the default in proc, the class will need to be serializable. That's why it's best to mark any classes you shove in session as Serializable from the beginning- then you can change the mechanism without having to edit your code.
RichardOD
Valid point but 1. `List<T>` is serializable if `T` is serializable. 2. The default session state mode is in-proc.
Mehrdad Afshari
@Mehrdad- I get what you meant and it is good you have a code sample. I'd just reword the "any object" in your answer.
RichardOD
A: 

Short answer: Yes

Long answer: Try it and see.

Juliet
A: 

Yes. Which platform are you writing for? ASP.NET C#?

List myList = new List(); Session["var"] = myList;

Then, to retrieve -

myList = (List)Session["var"];

Paul McLean