Information Technology Reference
In-Depth Information
Producing Enumerables and Enumerators
The previous example used a return type of IEnumerator<string> , which caused the compiler
to produce an enumerator class using generics. But you can specify other return types as well.
The return types you can specify are the following:
￿ IEnumerator (non-generic)
￿ IEnumerator<T> (generic—substitute an actual type for T )
￿ IEnumerable (non-generic)
￿ IEnumerable<T> (generic—substitute an actual type for T )
For the enumerator types, the compiler generates a nested class that contains the imple-
mentation of either the non-generic or generic enumerator, with the behavior specified by the
iterator block. It also produces the method that returns the enumerator.
For the enumerable types, it does even more. It produces a nested class that is both enumer-
able and the enumerator. The class, therefore, implements the GetEnumerator method. Notice
that this method is implemented as part of the nested class— not as part of the enclosing class.
Figure 20-10 illustrates the generic enumerable produced by an enumerable iterator.
￿
The iterator's code is shown on the left side of the figure, and shows that its return type
is IEnumerable<string> .
￿
On the right side of the figure, the diagram shows that the nested class implements both
IEnumerator<string> and IEnumerable<string> .
Figure 20-10. The compiler produces a class that is both an enumerable and an enumerator.
It also produces the method that returns the class object.
Search WWH ::




Custom Search