VB Array Assignment: 3 Methods to Assign Values
In VB, there are several ways to assign values to an array.
- You can use an array initializer to directly assign values to an array by using curly braces when declaring the array, for example:
Dim arr() As Integer = {1, 2, 3, 4, 5}
- Assign values one by one using a for loop: You can use a for loop to assign values to an array one by one, for example:
Dim arr(4) As Integer
For i As Integer = 0 To 4
arr(i) = i + 1
Next
- By using the Split function: you can split a string into array elements, for example:
Dim str As String = "1,2,3,4,5"
Dim arr() As String = str.Split(",")
- By using the CreateInstance method of the Array class, you can dynamically create an array and assign values to it, for example:
Dim arr As Array = Array.CreateInstance(GetType(Integer), 5)
For i As Integer = 0 To 4
arr(i) = i + 1
Next