How to create Dynamic Array

11,664

Solution 1

If we were in 2003 then yes, ArrayList could have worked fine but now I would recommend you using a generic List<T> which will be type safe and you don't need casting.

So you could have the following collection:

List<int> productIds = new List<int>();
productIds.Add(1);
productIds.Add(2);

Solution 2

The ArrayList is the usual .NET 1.x solution for this problem. If you are using .NET 2.0 or later, use a simple generic list (List<T>).

Like this:

var myIDs = new List<int>();

You can add items with the Add method.

myIDs.Add(2);
myIDs.Add(42);

You can assign it to a session variable this way:

Session["IdList"] = myIDs;

And you can recover it:

var stuff = (List<int>)Session["IdList"];

Hope this helps

Share:
11,664
Patrick Hofman
Author by

Patrick Hofman

Now in beta: query the Stack Exchange API real-time using SQL. See online-sql-editor.com and select Stack Exchange. Working on one of our newest products for accessing Exact Online, SQL Server, MySQL, Oracle, and others through Excel and Word. Also working on our free multi-database Query Tool (also supports real-time querying of exact-online): Feel free to contact me at patrick.hofman at [invantive] dot com

Updated on June 04, 2022

Comments

  • Patrick Hofman
    Patrick Hofman almost 2 years

    What would be the best way to create a dynamic array for a user to add products to a basket then store them in a session variable, I have been told serilizable arrays would work however when looking online for a solution I came accross an ArrayList which seemed perfect but I can't seem to implement it.

    I have a separate class called Basket with:

    ArrayList basketItems = new ArrayList();
    

    I need to be able to select a product from a gridview using the select link or alternatively using a listview and using my own button to then add the bookID to the array, which will then be stored in a session variable and sent to a basket page where the bookID will be used again against a SQL table to output the details of the book etc.

    • Win
      Win over 13 years
      You should accept an answer by clicking the checkmark if the answer is want you are looking for. It will help the community.