Loosening Up with C# Collections

By John Paul Mueller, Bill Sempf, Chuck Sphar

Often an array is the simplest, most straightforward way to deal with a list of Students or a list of doubles. You also encounter many places in the .NET Framework class library that require the use of arrays. But arrays have a couple of fairly serious limitations that sometimes get in your way. At such times, you’ll appreciate the extensive C# repertoire of more flexible collection classes. Although arrays have the advantage of simplicity and can have multiple dimensions, they suffer from two important limitations:

  • A program must declare the size of an array when it’s created. Unlike Visual Basic, C# doesn’t let you change the size of an array after it’s defined. For example, you might not know up front how big the array needs to be.
  • Inserting or removing an element in the middle of an array is wildly inefficient. You have to move around all the elements to make room. In a big array, that can be a huge, time-consuming job.

Most collections, on the other hand, make it much easier to add, insert, or remove elements, and you can resize them as needed, right in midstream. In fact, most collections usually take care of resizing automatically.

If you need a multidimensional data structure, use an array. No collection allows multiple dimensions (although you can create some elaborate data structures, such as collections of arrays or collections of collections). Arrays and collections have some characteristics in common:

  • Each can contain elements of only one type. You must specify that type in your code, at compile time, and after you declare the type, it can’t change.
  • As with arrays, you can access most collections with array-like syntax using square brackets to specify an index: myList[3] = “Joe”.
  • Both collections and arrays have methods and properties. Thus, to find the number of elements in the following smallPrimeNumbers array, you call its Length property:

var smallPrimeNumbers = new [] { 2, 3, 5, 7, 11, 13 };

int numElements = smallPrimeNumbers.Length; // Result is 6.

With a collection, you call its Count property:

List<int> smallPrimes = new List<int> { 2, 3, 5, 7, 11, 13 };

// Collections have a Count property.

int numElements = smallPrimes.Count;

Check out class Array in C# Language Help to see what other methods and properties it has (7 public properties and 36 public methods).