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

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