There are many different collection structures in VB.NET but I wanted to explain a bit about the ones I use most often. I'm going to discuss arrays, arraylists, generic lists, hashtables and dictionaries.
Arrays
An Array is strongly-typed but has a fixed number of items. I use this structure when I know exactly what I want to put into it and I don't want to enumerate through the collection, like the example below.
Dim bools As Boolean() = {True, False, False}
If bools(0) Then
Debug.WriteLine("First item in array is True.")
End If
ArrayLists
An ArrayList is an enumerable collection that can contain various datatypes. I use this structure when I have several miscellaneous pieces of information that I want to pass back from a function but don't want to define a custom type (I'm not developing on the 3.5 framework so I can't make use of ambiguous types yet). Here's an example.
Dim values As New ArrayList
values.Add(1)
values.Add("text")
values.Add(True)
For Each obj As Object In values
If TypeOf obj Is Integer Then
myInteger = DirectCast(obj, Integer)
ElseIf TypeOf obj Is Boolean Then
myBoolean = DirectCast(obj, Boolean)
Else
myString = DirectCast(obj, String)
End If
Next
Generic Lists or List(Of T)
A List(Of T) is essentially the same as an ArrayList except it is strongly-typed (where T is the type you are using) so you don't have to cast or convert the object into the type that you're expecting. I tend to use this structure the most often. Here's an example.
Dim colors As New List(Of Color)
colors.Add(Color.Maroon)
colors.Add(Color.Gold)
For Each clr As Color In colors
Debug.WriteLine(clr.Name)
Next
Hashtables
A Hashtable is like an ArrayList except each item in the ArrayList has a unique identifier, called a key. It is loosely-typed for both the keys and the values. I use this structure when I want to be very generic in my collection but want to be able to immediately pull out a value for a known key. You can also loop through the keys (or the values) if needed. Here's an example (the first statement will write "hello" and the second will write "goodbye").
Dim hash As New Hashtable
hash.Add(1, "hello")
hash.Add(True, "goodbye")
Debug.WriteLine(hash(1))
For Each obj As Object In hash.Keys
If TypeOf obj Is Boolean AndAlso DirectCast(obj, Boolean) = True Then Debug.WriteLine(hash(obj))
Next
Dictionaries
A Dictionary is like the combination of a List(Of T) and a Hashtable because it is a strongly-typed collection of key-value pairs. I use these when I have several large collections of information with known types and I don't want to loop through the collections manually, especially not with nested looping. Here's an example.
Dim dict As New Dictionary(Of Integer, Color)
dict.Add(0, Color.Maroon)
dict.Add(1, Color.Gold)
Debug.WriteLine(dict(0).Name)
For Each i As Integer In dict.Keys
Debug.WriteLine(dict(i).Name)
Next
Feel free to post a comment if you have something constructive to add. I'm always interested in new ways to manipulate collections.