10.26.05
Fully functional strong typed collections
If you’ve done OOP (Object Oriented Programming) in VB6, you’ve probably made instances of your custom-made classes. Maybe you even had a sort of grouping mechanism, a way for storing multiple instances of classes. That’s what this FAQ is about!
In my examples, I will use a Customer Class. This class is a basic data-class containing information about a specific customer.
There are several ways for keeping multiple instances :
- Array : easy to use
Drawbacks : pre-defined size, slow searching - Collection : fast searching, no pre-defined size, for-each loops, …
- Dictionary : same as Collection
One common drawback of these structures is that there is no control of the type of objects you store. For example, in a Collection you could add Customer-objects, but also (in the same collection object) some basic strings. This is bad, because most of the time you want only Customer-objects in your collection.
A way to overcome this problem is to encapsulate the collection in custom made collection class :
Code:
Public Property Get Item(Index As Integer) As Customer
Set Item = c.Item(Index)
End Property
But by doing this, you loose the for-each loop functionality of your collection.
Code:
For Each c In custColl
’Do Stuff
Next
The trick is to implement the NewEnum property in your collection Class. If you’ve added this property, you can use the for-each structure to loop trough your objects in your collection.
Code:
Set NewEnum = c.[_NewEnum]
End Property
Implementing this is only 1 step of the procedure to make it work. The next thing you have to do is setting the Procedure settings of the NewEnum property :
- Click ‘Tools’ menu -> ‘Procedure Attributes…’
- Select ‘NewEnum’ in the Name list
- Click the ‘Advanced>>>’ button
- And type ‘-4′ in the ‘Procedure ID’ combo. This item is not in the list, so you have to type it manually.
- Click ok
Now you have created a fully functional strong typed collection!! For a complete implementation and a test project, see my added VB project.