How to: Convert a Custom Collection to a Visual Basic Typed Collection

A Visual Basic 6.0 custom collection limits the contents of a collection to one particular class. This is also known as a typed collection. Visual Basic 2008 provides several options for creating typed classes from Visual Basic 6.0 custom collections. This topic contains three procedures, each showing a different option.

This topic assumes that the Visual Basic 6.0 custom collection has been created using the Class Builder Utility. Such a collection has the following members:

  • Add   Adds a new instance of the custom class to the collection.

  • Item   Returns an instance from the collection based on an index into the collection.

  • Count   Returns the number of instances in the collection.

  • Remove   Removes an instance from the collection based on an index into the collection.

  • Enumeration   Supports enumeration using the For Each syntax.

To use the Upgrade Wizard to create a collection

  • Open the Visual Basic 6.0 project in Visual Basic 2008. For a collection class named Forest that contains instances of the Tree class, the upgraded code is shown below. The advantage of this method is that no changes to the code are required.

    ' For this example, the Tree class has no members.Option Strict Off
    Option Explicit OnFriendClass Tree
    EndClassFriendClass Forest
      Implements System.Collections.IEnumerable
      'local variable to hold collectionPrivate mCol As Collection
    
      PublicFunction Add(OptionalByRef sKey AsString = "") As Tree
        'create a new objectDim objNewMember As Tree
        objNewMember = New Tree
        'set the properties passed into the methodIf Len(sKey) = 0 Then
          mCol.Add(objNewMember)
        Else
          mCol.Add(objNewMember, sKey)
        EndIf    'return the object created
        Add = objNewMember
        'UPGRADE_NOTE: Object objNewMember may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1029"'
    
        objNewMember = NothingEndFunctionDefaultPublicReadOnlyProperty Item(ByVal vntIndexKey _
        AsObject) As Tree
        Get      'used when referencing an element in the collection      'vntIndexKey contains either the Index or Key to the collection,      'this is why it is declared as a Variant      'Syntax: Set foo = x.Item(xyz) or Set foo = x.Item(5)
          Item = mCol.Item(vntIndexKey)
        EndGetEndPropertyPublicReadOnlyProperty Count() AsIntegerGet      'used when retrieving the number of elements in the      'collection. Syntax: Debug.Print x.Count
          Count = mCol.Count()
        EndGetEndProperty
      'UPGRADE_NOTE: NewEnum property was commented out. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1054"'
      'Public ReadOnly Property NewEnum() As stdole.IUnknown    'Get      'this property allows you to enumerate      'this collection with the For...Each syntax      'NewEnum = mCol._NewEnum    'End Get  'End PropertyPublicFunction GetEnumerator() As System.Collections.IEnumerator _
        Implements System.Collections.IEnumerable.GetEnumerator
        'UPGRADE_TODO: Uncomment and change the following line to return the collection enumerator. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1055"'
        'GetEnumerator = mCol.GetEnumeratorEndFunctionPublicSub Remove(ByRef vntIndexKey AsObject)
        'used when removing an element from the collection    'vntIndexKey contains either the Index or Key, which is why    'it is declared as a Variant    'Syntax: x.Remove(xyz)
        mCol.Remove(vntIndexKey)
      EndSub
      'UPGRADE_NOTE: Class_Initialize was upgraded to Class_Initialize_Renamed. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1061"'PrivateSub Class_Initialize_Renamed()
        'creates the collection when this class is created
        mCol = New Collection
      EndSubPublicSubNew()
        MyBase.New()
        Class_Initialize_Renamed()
      EndSub
      'UPGRADE_NOTE: Class_Terminate was upgraded to Class_Terminate_Renamed. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1061"'PrivateSub Class_Terminate_Renamed()
        'destroys collection when this class is terminated    'UPGRADE_NOTE: Object mCol may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1029"'
    
        mCol = NothingEndSubProtectedOverridesSub Finalize()
        Class_Terminate_Renamed()
        MyBase.Finalize()
      EndSubEndClass
    

The .NET Framework and Visual Basic 2008 offer several generic collections. The advantage to using generic classes is that very little code is required to implement the class.

To create a collection using generic collections

  1. Create the class definition. Here is an example of a Tree class:

    PublicClass Tree
        Public Species AsStringEndClass
    
  2. Create a generic list class from the .NET Framework. This declaration essentially replaces the entire Forest class in the procedure above named "To use the Upgrade Wizard to create a collection."

    Dim forest AsNew System.Collections.Generic.List(Of Tree)
    
  3. Write code to access the list object. The following code adds five instances of the Tree class to the collection and then prints them out.

    For count AsInteger = 1 To 5
        Dim sapling AsNew Tree
        sapling.Species = "oak"
        Forest.Add(sapling)
    NextForEach sapling As Tree In Forest
        MsgBox(sapling.Species)
    Next
    

The .NET Framework includes the CollectionBase class. Typed collections are created by inheriting from CollectionBase. This method uses less code than the Upgrade Wizard method, but more than the generics solution. It is more flexible than the generics solution, because the programmer can add additional members to the collection class.

To create a collection from the CollectionBase class

  1. Create the class definition. Here is an example of a Tree class:

    PublicClass Tree
        Public Species AsStringEndClass
    
  2. Create a class that inherits from the CollectionBase class. At a minimum, add an Add method and an Item property. These make the collection class strongly-typed.

    Class TreeCollection
      Inherits System.Collections.CollectionBase
    
      PublicSub Add(ByVal value As Tree)
        Me.List.Add(value)
      EndSubDefaultPublicProperty Item(ByVal index AsInteger) As Tree
          GetReturnCType(Me.List(index), Tree)
          EndGetSet(ByVal value As Tree)
              If index <= Me.Count - 1 ThenMe.List(index) = value
              ElseThrowNew IndexOutOfRangeException()
              EndIfEndSetEndPropertyEndClass
    
  3. Write code to access the list object. The following code adds five instances of the Tree class to the collection and then prints them out.

    Dim forest AsNew TreeCollection
    
    For count AsInteger = 1 To 5
        Dim sapling AsNew Tree
        sapling.Species = "oak"
        Forest.Add(sapling)
    NextForEach sapling As Tree In Forest
        MsgBox(sapling.Species)
    Next
    

See Also

Reference

List

CollectionBase

IEnumerable