Arrays
11.1 Declaring Arrays
⚠️ In VB, Dim arr(4) creates 5 elements (0 to 4). The number is the upper bound.
Dim numbers(4) As Integer ' 5 elements: indices 0..4 (upper bound, NOT length!)
Dim names() As String = {"Ana", "Bo", "Cy"}
Dim scores = New Integer() {90, 85, 77}
Dim empty() As Integer = {}
Dim matrix(2, 3) As Double ' 3 x 4 two-dimensional
Dim grid = New Integer(,) {{1, 2}, {3, 4}}
Dim jagged()() As Integer = {New Integer() {1}, New Integer() {2, 3}} ' array of arrays
numbers(0) = 10
Console.WriteLine(names.Length & " " & names(names.Length - 1))
Console.WriteLine(matrix.GetLength(0) & "x" & matrix.GetLength(1))
Console.WriteLine(UBound(numbers) & " " & numbers.GetUpperBound(0))11.2 Resizing Arrays
For dynamic sizes, prefer List(Of T) (Module 12).
Dim items(2) As String
ReDim Preserve items(5) ' grow, keeping existing values
ReDim items(10) ' resize and clear
Array.Resize(items, 20)
Erase items ' set to Nothing11.3 Array Operations
Dim arr = {5, 3, 8, 1, 9}
Array.Sort(arr)
Array.Reverse(arr)
Dim idx = Array.IndexOf(arr, 8)
Dim found = Array.Find(arr, Function(x) x > 5)
Dim all = Array.FindAll(arr, Function(x) x Mod 2 = 1)
Dim exists = Array.Exists(arr, Function(x) x = 3)
Dim copy = CType(arr.Clone(), Integer())
Array.Copy(arr, copy, arr.Length)
Array.Clear(arr, 0, arr.Length)
Dim pos = Array.BinarySearch(arr, 8) ' the array must be sorted
Console.WriteLine(String.Join(", ", arr))
Console.WriteLine(arr.Sum() & " " & arr.Max() & " " & arr.Average()) ' LINQ11.4 Looping Through Multidimensional Arrays
For row = 0 To matrix.GetUpperBound(0)
For col = 0 To matrix.GetUpperBound(1)
matrix(row, col) = row * col
Next
Next