O'Reilly logo

Programming Visual Basic 2005 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

Generics

The goal of generics is to create collections that are "type safe" but that can be reused at design time with any type. Thus, the designer of a generic List would like to be able to designate that the List class can hold any type of data, but a specific type will be declared when the List class is used, and the compiler will enforce the type safety.

Generic List Class

The classic problem with the Array type is its fixed size. If you do not know in advance how many objects an array will 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).

Suppose you create a program that gathers input from a web site. As you find objects (strings, books, values, etc.), you will add them to the array, but you have no idea how many objects you'll collect in any given session. The classic fixed-size array is not a good choice, as you can't predict how large an array you'll need.

The List class is like an array whose size is dynamically increased as required. Lists provide a number of useful methods and properties. Some of the most important are shown in Table 17-2.

Table 17-2. List methods and properties

Method or property

Purpose

The idiom in the Framework Class Library is to provide an Item property for collection classes that is implemented as an indexer in Visual Basic 2005.

Capacity

Property to get or set the number of elements the List can contain. This value is increased automatically if count exceeds capacity. ...

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