Creating Generic List Collections in C#

Leave a Comment
The pattern for using a generic List collection is similar to arrays. You declare the List, populate it's members, then access the members. Here's a code example of how to use a List:
    List<int> myInts = new List<int>();
    myInts.Add(1);
    myInts.Add(2);
    myInts.Add(3);
    for (int i = 0; i < myInts.Count; i++)
    {
        Console.WriteLine("MyInts: {0}", myInts[i]);
    }

The first thing you should notice is the generic collection List<int>, which is referred to as List of int. If you looked in the documentation for this class, you would find that it is defined as List<T>, where T could be any type.  For example, if you wanted the list to work on string or Customer objects, you could define them as List<string> or List<Customer> and they would hold only string or Customer objects. In the example above, myInts holds only type int.

Using the Add method, you can add as many int objects to the collection as you want. This is different from arrays, which have a fixed size. The List<T> class has many more methods you can use, such as Contains, Remove, and more.

There are two parts of the for loop that you need to know about. First, the condition uses the Count property of myInts. This is another difference between collections and arrays in that an array uses a Length property for the same thing. Next, the way to read from a specific position in the List<T> collection, myInts[i], is the exact same syntax you use with arrays.

The next time you start to use a single-dimension array, consider using a List<T> instead. That said, be sure to let your solution fit the problem and use the best tool for the job.  i.e. it's common to work with byte[] in many places in the .NET Framework.

0 comments:

Post a Comment