O'Reilly logo

Learning C# 3.0 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

We spent time explaining what generic collections are and how they work so that you’d have an appreciation for how they’re created and what they can do. Most of the time, you won’t need to create your own collection, because the .NET Framework provides four very useful generic collections, as we discussed earlier (List, Stack, Queue, and Dictionary). We describe each 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 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

Property that .NET requires for the List class as an indexer; you’ll never see this in C#; you can use the standard [] syntax instead

Add( )

Public method to add an object ...

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