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 |
---|---|
|
Enumerates through a collection using a |
|
Implemented by all collections to provide the |
|
Compares two objects held in a collection so that the collection can be sorted. |
|
Used by array-indexable collections. |
|
Used for key/value-based collections such as
|
|
Allows enumeration with |
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 ...
Get Programming C#, Third Edition 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.