Collections in Visual Basic are needed to store a group of objects or values in a variable. Standard collections like Collection, ArrayList, and generic List(Of T) provide various methods for accessing, adding, and removing elements, and differ in type safety, performance, and features.
In classic VB6, there was only the typed collection Collection. In .NET, more powerful structures appeared, including ArrayList (an old universal type without strict typing) and modern generic collections like List(Of T), introduced in .NET 2.0.
The main challenge is choosing the suitable collection for the project’s needs. Collections without strict typing (ArrayList, Collection) can lead to runtime errors or performance issues. Generic collections require parameterization but offer maximum safety and ease of use with types.
Use the old collection Collection only for interaction with legacy code, and prefer List(Of T) for new projects. The ArrayList is only useful when there is no information about the element types, but it's better to use List(Of Object) or other collections from Generic in this case.
Example code:
' Collection Dim coll As New Collection() coll.Add("Hello") coll.Add(123) ' ArrayList Dim arr As New ArrayList() arr.Add("World") arr.Add(456) ' List(Of T) Dim list As New List(Of Integer)() list.Add(789) list.Add(101112)
Key features:
What is the difference between Collection and an array in Visual Basic?
An array fixes its size upon initialization, holds elements of a single type, and supports fast access by index. A Collection dynamically increases, can hold objects of different types, and supports key access (but is non-indexable in VB6).
What happens if you try to add an object with the same key in Collection?
Trying to add an element with an already existing key will result in a runtime error "Key already exists in collection".
Dim c As New Collection() c.Add("one", "a") c.Add("two", "a") ' Error
Can you cast ArrayList to List(Of T) in the usual way?
No, standard conversion is not possible — you will have to manually create a new List(Of T) and copy suitable elements, otherwise, runtime errors will occur due to the lack of strict typing in ArrayList.
In a client storage project, an ArrayList was used, where a string was accidentally added instead of a Client object. During processing, a type cast error occurs, which is hard to trace.
Pros:
Cons:
Strictly typed List(Of Client) is used, and the entire code compiles with Strict On option. Errors are detected at compile time, and the structure is easily extended with new LINQ methods.
Pros:
Cons: