The biggest benefit of implementing these methods
explicitly is to help you avoid their use at compile time.
How Iteration Works
You??™ve seen how you can use the For . . . Each statement to conveniently iterate over a
collection of objects, including a System.Array, ArrayList, List(Of T), and so on. How does
this work? The answer is that each collection that expects to work with For . . . Each must
implement the IEnumerable(Of T) or IEnumerable interface. For . . . Each then obtains an
object that knows how to enumerate, or iterate over, the elements in the collection. The
iterator object obtained from IEnumerable(Of T) must implement the IEnumerator(Of T) or
IEnumerator interface. Generic collection types typically implement IEnumerable(Of T), and
the enumerator object implements IEnumerator(Of T). IEnumerable(Of T) derives from
IEnumerable, and IEnumerator(Of T) derives from IEnumerator. This allows you to use generic
collections in places where nongeneric collections are used. Strictly speaking, your collection
types are not required to implement enumerators, and users can iterate through the collection
using a For loop if you provide an index operator by implementing IList(Of T), for example.
CHAPTER 10 n ARRAYS AND COLLECTIONS 211
In the rest of this section, we??™ll quickly go over the salient points of creating enumerators
in VB.
Pages:
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353