Collection is an object container. In general, a collection contains multiple values and provided ways to iterate through them or add and delete them. Just like the collection framework in Java. The .NET platform has its own collection framework which is a part of the .NET framework.

But its just as easy as in Java platform to use it.

There are several different kinds of collection in VB.NET. For example:

 
Microsoft.VisualBasic.Collection
System.Collections
System.Collections.Generic
System.Collections.Specialized
 

And this post dedicated to the first one Microsoft.VisualBasic.Collection. This type mimics the behavior of VB 6 collections and also expose ICollection interface.

Lets create a new collection.

 
Private myCollection As New Collection
 

The Add method

The first thing you want to do now is add something into the collection. The Add method accept a parameter of type Object. Means you can add anything to the collection.

 
Public Class TestCollection
 
        Private myCollection As New Collection()
 
        Public Sub Test1()
            ' add strings
            myCollection.Add("value1")
            myCollection.Add("value2")
            myCollection.Add("value3")
 
            ' add differnt types of object
            myCollection.Add(10)
            myCollection.Add(10.0)
            myCollection.Add(True)
            msg("how many items in collection: " + myCollection.Count.ToString())
        End Sub
    End Class
 

Iterate through the collection

Using For Each statement to iterate through a collection , like this.

 
            ' iterate
            For Each obj As Object In myCollection
                msg(" item value: " + obj.ToString())
            Next
 

The items in collection can also be referenced by their index value. Just like iterate through an array.

 
            Dim i As Integer
            For i = 1 To myCollection.Count
                msg(i.ToString() + "th item value: " + myCollection(i).ToString())
            Next