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:
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
Very nice. Thank you for your comment.
Post a Comment