C# Generic Lists

I remember the many frustrating hours I spent in C and C++ dealing with arrays. I remember the nights hunting down the cause of a bug, only to realize it was the result of exceeding my array bounds. I remember having to redefine and copy arrays when I wanted to change the number of elements in the array, because in C, array length is fixed.

When I learned about linked lists, it got better. Rather than allocating a specific chunk of memory, like a static array did, linked lists are much more flexible because each element simply contains a memory pointer to the next one. This is very flexible, because you can add, remove, or change the nodes in a linked list quite easily.

However, accessing the elements of a linked list is more complicated than accessing an array. In an array, if you wanted to loop through and output all the elements of an array, you could do the following:

for (int i=0; i < sizeof(arrMyArray) / sizeof(int); i++) {
cout << arrMyArray[i] << endl;
}

A linked list is not much more complicated:

for (LinkedList objNode = objMyLinkedList; objNode != null; objNode = objMyLinkedList->Next) {
cout << objMyLinkedList.m_Data << endl;
}

However, the linked list really showed its limitation when trying to access elements randomly. You can do the following with a C array, but not a linked list:

cout << arrMyArray[27];

Thankfully, in C++, the standard template library introduced vectors, which are a kind of dynamic array. The stl::vector saved me a lot of headaches once I learned how to use it.

In C#, you can use what are called generic lists, which are like C++ vectors. As I was programming my GEDCOM importer last night, I really came to appreciate generic lists. They have all the conveniences of the C array and the C++ vector. You can create them dynamically, but you can also access them just like an array. They’re really easy to use, too:

using System.Collections.Generic;

List intNumbers = new List();

intNumbers.Add(3);
intNumbers.Add(7);
intNumbers.Add(8);

for (int i = 0; i < intNumbers.Count; i++) {
Console.WriteLine(intNumbers[i] + “\n”);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>