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 |
ICollection |
Implemented by all collections to provide the |
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 |
IDictionaryEnumerator |
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 than ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access