Collections in VB.NET are very similar to arrays. They are used to store a number of values (or
variables), so that you can process them all.
Let us see how to define a Collections in VB.NET. There are two ways to define a collection:
Dim C As New Collection
In this example you create a collection object that is ready to be used. So you can add, remove elements, get the number of items, or do whatever you want with the collection directly. Another way is:
Dim C As Collection
here C is not ready yet to be used. It does not point to a collection yet. You can never use it. To be able to use it later on in the code you should write:
C = New Collection
This will allow you to use the collection without any problem. The first method of defining a collection is the one you will probably use the most.
Difference between collections in VB.NET and array:
There are a number of differences between arrays and collections.
- First difference is that the indexing for arrays starts with zero, while for a collection it starts with 1. To understand this, consider the image below:
- All Array elements has the same data type.
So if you have an array:
Dim A(0 To 9) As Integer
then A(0), A(1), A(2)… A(9) are all Integers. Collections on the other hand do not require this. You can store integers, reals, strings, bytes,… etc. in the same collection.
This can be illustrated below:
- Usually you will use the same data type for all elements of the collection; however you still have the option to use different data types whenever you need to.
- Another difference between arrays and collections is that collections can add elements and remove elements directly and change in size without any need for some kind of processing, while arrays are fixed in size, and you cannot insert values at specific locations at random.