#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. Pingback: Dew Drop – May 1, 2013 (#1,538) | Alvin Ashcraft's Morning Dew

  2. “You can use the List class, defined in System.Collections.Generic, to store a list of objects that all have the same type.”

    “You can think of a List as an array that grows or shrinks in size as you add or remove elements.”

    Nice, succinct explanation! Too many references (Microsoft’s being one of the worst) make this simple concept so complicated.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: