
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Creating an Iterator on a Non-generic Type
|
335
// Iterator
IEnumerator<T> IEnumerable<T>.GetEnumerator( )
{
for (int index = 0; index < _items.Count; index++)
{
yield return (_items[index]);
}
}
IEnumerator IEnumerable.GetEnumerator( )
{
for (int index = 0; index < _items.Count; index++)
{
yield return (_items[index]);
}
}
}
This makes it more apparent that this class supports enumeration. You can also
specify a concrete type in place of
T in IEnumerable<T>, such as IEnumerable<string>,
if you wish that class to enumerate values only of type
string. Regardless of the
method you choose, the operation of the iterator and the
foreach loop is identical.
See Also
See the “Iterators,” “IEnumerator Interface,” and “IEnumerable Interface” topics in
the MSDN documentation.
6.4 Creating an Iterator on a Non-generic Type
Problem
You want elements contained in your non-generic type to be enumerated using the
foreach statement.
Solution
Add an iterator to your non-generic type, as shown here:
public class NGShoppingList
{
public NGShoppingList( ) {}
private List<string> _items = new List<string>( );
public void AddItem(string item)
{
_items.Add(item);
}
public IEnumerator<string> GetEnumerator( )