Tim on October 27th, 2007

Dim, ReDim, ReDim Preseve, Repeat. Sound familiar? If so, maybe you want to look into generic collections. In the System.Collections namespace the ArrayList class will give you a dynamically allocated list of objects that’s easy to use. You won’t need to worry about ReDim’ing the array if you need to add items, and you won’t have to deal with array indexing issues when adding/removing items.

Example using an array.

‘create the string array with an initial size
Dim values As String(1)

‘add a value
values(0) = “test 1″

‘…. do some work ….

‘now we need to add another value to the array,
‘so we need to do a ReDim
ReDim Preserve values(2)
values(1) = “test 2″

Now let’s rewrite the example using an ArrayList

‘create the arraylist
Dim values As New ArrayList()

‘add a value
values.Add(“test 1″)

‘…. do some work ….

‘now add another value, but there’s no need to ReDim
values.Add(“test 2″)

For me, there’s one drawback to ArrayList. Type safety. If you want compile time checking of the object types you’re adding to a collection, look at the generic List(Of Object) class in the System.Collections.Generic namespace. You’ll get type safety and a performance boost by using the generic List object, not to mention Intellisense support.

‘create the list
Dim values As New List(Of String)
values.Add(“test 1″)

You aren’t limited to a simple list either. There’s a sorted list, a dictionary, and a sorted dictionary. For me, the choice is easy. I use generic collections where I might have used an array before. That’s not saying I never use a simple array any more, but generic collections are definitely a good addition to my toolkit.

One Response to “A Case For Generics In VB.NET – Part 1”

Trackbacks/Pingbacks

  1. ScarTech » Blog Archive » A Case for Generics in VB.NET - Part 2

Leave a Reply

You will be able to edit your comment after submitting.