Collection Interfaces

The .NET Framework provides standard interfaces for enumerating, comparing, and creating collections. The key collection interfaces are listed in Table 9-2.

Table 9-2. Collection interfaces

Interface

Purpose

IEnumerable

Enumerates through a collection using a foreach statement.

ICollection

Implemented by all collections to provide the CopyTo( ) method as well as the Count, ISReadOnly, ISSynchronized, and SyncRoot properties.

IComparer

Compares two objects held in a collection so that the collection can be sorted.

IList

Used by array-indexable collections.

IDictionary

For key/value-based collections such as Hashtable and SortedList.

IDictionaryEnumerator

Allows enumeration with foreach of a collection that supports IDictionary.

The IEnumerable Interface

You can support the foreach statement in ListBoxTest by implementing the IEnumerable interface. IEnumerable has only one method, GetEnumerator( ) , whose job is to return a specialized implementation of IEnumerator. Thus, the semantics of an Enumerable class are that it can provide an Enumerator:

public IEnumerator GetEnumerator(  )
{
    return (IEnumerator) new ListBoxEnumerator(this);
}

The Enumerator must implement the IEnumerator methods and properties. These can be implemented either directly by the container class (in this case, ListBoxTest) or by a separate class. The latter approach is generally preferred because it encapsulates this responsibility in the Enumerator class rather than ...

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