How to: Define Collections in Your Classes (Visual Basic)

You can add a collection to one of your classes to manage groups of objects your class uses. The simplest way of doing this is to add a public variable of type Collection to your class. Consider a hypothetical class called widgetRepository that manages and exposes widget objects. You might create a widgetColl variable to refer to a widget collection, as discussed in the following procedure.

To define a simple collection in a class

  • Create a public variable to act as a collection for your objects.

    Public Class widgetRepository
        Public widgetColl As New Microsoft.VisualBasic.Collection()
        ' Insert code to implement additional functionality.
    End Class
    

    The class widgetRepository now has a public collection to which you can add widget objects. You can then use a For Each...Next Statement (Visual Basic) to process the collection elements, as the following code demonstrates.

    For Each aWidget As widget In widgetColl
        ' Insert code to process widgetColl elements
    Next aWidget
    

    The widgetColl collection defined in the preceding example is not strongly typed, which means you can add any type of object to it, not just widget objects. This can lead to type safety problems. For example, suppose you add a String to the collection, as in the following code.

    Dim notWidget As String = "This is not a widget object!"
    widgetColl.Add(notWidget)
    

    If you do this, the For Each loop in the previous procedure throws an ArgumentException exception at run time because an element of the collection is not of type widget.

    We recommend that you define a generic class when you want to ensure type safety. For more information and an example, see How to: Define Type-Safe Collections (Visual Basic).

Community Additions

ADD
Show: