What Makes a Collection Walk?

The For Each syntax provides a natural way to iterate through a collection. You don’t have to worry about how the collection is organized or what it does. For each trip through the loop, you just go to the next item. The designer of the collection determines what that means.

There’s nothing sacred about the way Visual Basic’s Collection class works. If you want to design your collection to iterate backward or to generate a random number for every iteration, that’s up to you. The problem is, Visual Basic doesn’t provide an easy way to make your collection work with For Each. But if you understand how collection iterations work, you can do the impossible (or at least the impractical). You just have to understand a few facts about the IEnumVARIANT interface.

The Component Object Model defines IEnumVARIANT as the standard way to iterate through data structures. Any collection class that wants to allow clients to walk through variant data should provide an iterator that implements IEnum­VARIANT. Any client program that wants to iterate through variant data classes that follow the standard can do so by calling the IEnumVARIANT ­methods.

That’s how Visual Basic’s For Each syntax works. When you write a For Each code block, Visual Basic calls the Next method of IEnumVARIANT for each ­iteration. The Collection class works with For Each because it provides an iterator class that implements the methods of IEnumVARIANT.

So how do you implement IEnumVARIANT? With great difficulty.