Array Lists

Imagine that your program asks the user for input or gathers input from a web site. As it finds objects (strings, books, values, etc.), you would like to add them to an array, but you have no idea how many objects you’ll collect in any given session.

It is difficult to use an array for such a purpose because you must declare the size of an Array object at compile time. If you try to add more objects than you’ve allocated memory for, the Array class throws an exception. If you do not know in advance how many objects your array will be required to hold, you run the risk of declaring either too small an array (and running out of room) or too large an array (and wasting memory).

The .NET Framework provides a class designed for just this situation. The ArrayList class is an array whose size is dynamically increased as required. The ArrayList class provides many useful methods and properties. Table 16-3 shows a few of the most important.

Table 16-3. ArrayList members

Method or property

Purpose

Capacity

Property containing the number of elements the array can currently hold

Count

Property to return the number of elements currently in the array

Item()

Method that gets or sets the element at the specified index. This is the indexer for the ArrayList class

Add()

Method to add an object to the ArrayList

Clear()

Method that removes all elements from the ArrayList

GetEnumerator()

Method that returns an enumerator to iterate an ArrayList

Insert()

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.