Chapter 16. Collection Interfaces and Types

A collection is a container that holds a group of objects. Collections are used to hold all the strings in a listbox, to hold all the employees in a company, to hold all the controls on a page, and so forth. You’ve already seen the simplest collection, the array (see Chapter 15). An array is a collection that provides an indexed list of elements, all of the same type.

The .NET Framework provides a number of already built and tested collection classes, including the ArrayList, Queue, and Stack. This chapter will explain how to use these collections and will provide examples of their use.

The Collection Interfaces

Every collection has certain shared characteristics, which are captured by the collection interfaces. The .NET Framework provides standard interfaces for enumerating, comparing, and creating collections.

Tip

Chapter 14 introduced interfaces, which create a contract that a class can fulfill. Implementing an interface allows clients of the class to know exactly what to expect from the class.

By implementing the collection interfaces, your custom class provides the same semantics as the collection classes available through the .NET Framework. Table 16-1 lists the key collection interfaces and their uses.

Table 16-1. The collection interfaces

Interface

Purpose

IEnumerable

Enumerates through a collection using a foreach statement

IEnumerator

Iterates over a collection and supports the foreach loop

ICollection

Implemented ...

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