#834 – Use a Generic List to Store a Collection of Objects

You can use the List<T> class, defined in System.Collections.Generic, to store a list of objects that all have the same type.  This generic list is one of several collection classes that allow you to store a collection of objects and manipulate the objects in the collection.

You can think of a List<T> as an array that grows or shrinks in size as you add or remove elements.  You can easily add and remove objects to a List<T>, as well as iterate through all of its elements.

You can store a collection of either value-typed or reference-typed objects in a List<T>.

            // Define a list of integers
            List<int> favNumbers = new List<int>();

            // Add a couple numbers to the list
            favNumbers.Add(5);
            favNumbers.Add(49);
            favNumbers.Add(8);
            favNumbers.Add(0);

            // Iterate through the list to get each int value
            foreach (int i in favNumbers)
                Console.WriteLine(i);

            // Remove 1st element (at position = 0)
            favNumbers.RemoveAt(0);

834-001

834-002

Advertisements