O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, 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

Framework Generic Collections

The .NET Framework provides four very useful generic collections , as enumerated earlier (List , Stack, Queue, and Dictionary). The most common case is that rather than writing your own collection, you’ll use one of the collection classes provided for you. Each is described in turn in the next few sections.

Generic Lists: List<T>

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).

The generic List class (which replaces the old non-generic ArrayList) is, essentially, an array whose size is dynamically increased as required. Lists provide a number of useful methods and properties for their manipulation.. Some of the most important are shown in Table 14-2.

Table 14-2. List properties and methods

Method or property

Purpose

Capacity

Property to get or set the number of elements the List can contain. This value is increased automatically if count exceeds capacity. You might set this value to reduce the number of reallocations, and you may call Trim( ) to reduce this value to the actual Count.

Count

Property to get the number of elements currently in the list.

Item( )

Gets or sets the element at the specified index. This is the indexer for the List class.[a]

Add( )

Public method to add an object to the List.

AddRange( )

Public method that adds the elements of an ...

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