10.26.05

Fully functional strong typed collections

Posted in Uncategorized at 8:33 am by aspnet

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:

Private c As New Collection

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:

Dim c As Customer
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:

Public Property Get NewEnum() As IUnknown
   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 :

  1. Click ‘Tools’ menu -> ‘Procedure Attributes…’
  2. Select ‘NewEnum’ in the Name list
  3. Click the ‘Advanced>>>’ button
  4. And type ‘-4′ in the ‘Procedure ID’ combo. This item is not in the list, so you have to type it manually.
  5. 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.

Leave a Comment