2.3.6 How to Add Items to a List

In order to add anything to a List we need to access the list's Add method and pass in an argument to add.


In order to properly add something to a List it needs to at least be of that type. To add a Food item to our Food List we need to pass in a Food type to the List class's Add method.

When we run the application and step over the call to Add we can see that the List's Count goes up.

We can continue adding Foods to the list by using the Add method.


Note: In this example we are reusing the food variable. Reusing variables is covered more in-depth in other articles. Just know that the List will contain two separate objects after this code executes.

When we execute the second Add method call, we can see that the Count of the List goes up again.

To see what objects are in the List, expand the List object and the [0] and the [1].


Note: Lists in programming always start at 0. Get used to it.

In this view you can see that the List has the Cheetah Chips and Meatloaf.