1. Computing

Using Arrays and Collections in VB.NET

By

6 of 6

Differences Between Arrays and Collections
Using Arrays and Collections in VB.NET

The main difference is that an array is a specific thing in VB. According to Microsoft, a collection is, "more of a concept than a definition." So the rules you have to follow to code arrays are clear and specific but collections have a lot of different forms and allow for more creativity.

Declaration

An array is declared by simply using parenthesis to indicate that a variable has an index. For example, Dim StringArray() is syntactically correct (although at least the size of the array will eventually have to be supplied).

A collection is typically an instance of a class and has to be declared with the New keyword to create the instance. Elements are added and deleted using methods. This code shows the difference.


Dim StringArray()
ReDim StringArray(10)
StringArray(0) = "ABCDEF"

Dim ListCollection As New List(Of String)
ListCollection.Add("ABCDEF")
ListCollection.Remove("ABCDEF")

Size

As the example above shows, an array has a fixed size unless the ReDim statement is used to change it. Collections are inherently variable in size.

Programming Syntax

Most of your programming with arrays will use methods of the Array object. In VB.NET 4.0, there are 97 methods of the Array class including whole groups of different "sort" methods and "find" methods that can generally be applied to any array.

You typically use a different type of collection to accomplish different programming goals. For example, you would use a Stack collection for LIFO (Last In, First Out) processing and a Queue collection for FIFO (First In, First Out) processing and each has fewer than 20 methods. These methods don't include either find or sort because that would be contrary to the whole concept of stacks and queues.

Keyed Access

You always have to reference an array using an index value. We've seen several examples of this. Many collections, however, give you the option of using a key value to access the elements. The most basic example is a Dictionary collection. The illustration shows three elements being added to a Dictionary and the middle one being displayed in the Output window using the key value.


Dim aDictionaryCollection As _
    New Dictionary(Of String, String)

aDictionaryCollection.Add("key1", "Element1")
aDictionaryCollection.Add("key2", "Element2")
aDictionaryCollection.Add("key3", "Element3")

Console.WriteLine(
    aDictionaryCollection("key2"))

The use of a key in other collection classes isn't quite so straightforward, but they all use this basic idea.

  1. About.com
  2. Computing
  3. Visual Basic
  4. Learn VB.NET
  5. Using Arrays and Collections in VB.NET

©2014 About.com. All rights reserved.