O'Reilly logo

Learning Visual Basic .NET by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 will throw 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. A few of the most important are shown in Table 15-3.

Table 15-3. ArrayList members

Method or property

Purpose

Capacity

Property containing the number of elements the array can currently hold.

Count

Property that returns 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 that adds an object to the ArrayList.

Clear( )

Method that removes all elements from the ArrayList.

GetEnumerator( )

Method that returns an enumerator to iterate ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required