14.4. Implement an Enumerable Type Using a Custom Iterator

Problem

You need to create a collection type whose contents you can enumerate using a For Each statement.

Solution

Implement the interface System.Collections.IEnumerable or System.Collections.Generic.IEnumerable(Of T) on your collection type. The GetEnumerator method of the IEnumerable and IEnumerable(Of T) interfaces returns an enumerator, which is an object that implements either the System.Collections.IEnumerator or System.Collections.Generic.IEnumerator(Of T) interface, respectively. The IEnumerator and IEnumerator(Of T) interfaces define the methods used by the For Each statement to enumerate the collection.

Implement a private iterator class within the enumerable type that implements ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.