Lists are a very useful data structure like arrays. They have the added benefit of dynamically growinging of shrinking as you add or delete items.

As with arrays, you can use them to store simple data types (check here). Here you'll learn how to store objects. In this example we will assume you are making objects from a class called Shape. We will add them to a list called myShapesList.


Step 1. Create the List

To create a list you give it a name (e.g. myShapesList). You must also define the data type (within angle brackets) on both the left and right hand side of the statement, in this case Shape.

List<Shape> myShapesList = new List<Shape>();

Step 2: Add items

You need to create an instance of the object before adding:

Shapes = new Shape();
myShapesList.add(s);

Here's a more compact version.

myShapesList.add(newShape());

Step 3: Retrieve an item

The following code will get the first student object from the list.

Shapes = myShapesList.get(0);

Step 4: Loop through the entire array

The following code will get each item from myNumbers and store into the local variable val.

for (int x = 0; x < myShapesList.size(); x++)
{
    Shapes = myShapesList.get(x); 
    // do something with val
}

An easier loop: foreach

The following code will retrieve each item in order and store in val.

foreach (Shape s in myShapesList)
{
    // do something with the s object
}