Thursday, October 04, 2007

Dynamically create a simple array in VB.Net

Using an array is more efficient than a collection if an array can suffice, but in the past I have found myself resorting to using a collection simply because I did not know in advance the number of elements needed until runtime. Turns out it is easy to create a simple system array at runtime and specify the length of the array at that time.

For example, to create a string array of 5 elements (0 to 4):
Dim MyArray as System.Array
MyArray = System.Array.CreateInstance(GetType(String),5))

which is equivalent to the following code at compile time:
Dim MyArray(4) as String

The same technique can be used to dynamically create arrays of any type at runtime.

Note that the above example assumes Option Strict is off. If Option Strict is on, you must use the .SetValue and .GetValue methods to access the array elements. If Option Strict is on, a proper code sample would be:

'Option Strict On
Dim mya As System.Array
mya = System.Array.CreateInstance(GetType(String), 3)
mya.SetValue("Word1", 0)
mya.SetValue("Word2", 1)
mya.SetValue("Word3", 2)
MessageBox.Show("Element (2) is " & _
Convert.ToString(mya.GetValue(2))) 'Returns "Word3"

Hope that helps.
Joe Kunk

2 comments:

Anonymous said...

You can also do the following:
Dim s() as string

s = CType(Array.CreateInstance(GetType(String), 3), String())

Now you don't have to call GetValue SetValue, even with Strict turned on

Joe Kunk said...

Very nice. Thank you for your comment.