Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท Control Flow and Procedures

Arrays in VB.NET

Learn Visual Basic .NET arrays: declaring and initializing, the upper-bound rule, ReDim Preserve, multidimensional and jagged arrays, sorting, searching, copying and the most common array mistakes.

An array holds a fixed number of values of the same type, stored one after another and accessed by an index. Arrays are the simplest collection, and many other structures (lists, strings, buffers) build on them. VB.NET arrays have a quirk that trips up newcomers and C# programmers alike: the number you give in a declaration is the upper bound, not the length. This lesson covers declaring, filling, resizing and searching arrays. Listings are VB.NET (read-only); runnable C# stand-ins use the identical System.Array class.

Declaring and initializing

VB
Dim scores(4) As Integer                 ' 5 elements: indexes 0 to 4
Dim names() As String = {"Ada", "Linus", "Grace"}   ' size inferred: 3
Dim primes = {2, 3, 5, 7, 11}            ' type inferred: Integer()
Dim empty(-1) As Integer                 ' a zero-length array
Dim grid As Integer() = New Integer(2) {}   ' also 3 elements

Dim scores(4) creates five elements (0 to 4). Every element starts at the default value: 0, False or Nothing. Read and write with parentheses:

VB
scores(0) = 90
scores(4) = 75
Console.WriteLine(scores(0) + scores(4))     ' 165
Console.WriteLine(scores.Length)             ' 5
Console.WriteLine(scores.GetUpperBound(0))   ' 4

An index outside 0..Length-1 throws IndexOutOfRangeException. Arrays are reference types: assigning one array variable to another shares the same data (use Clone or Array.Copy to duplicate).

C# Stand-in (C#): length versus upper bound

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Looping over arrays

VB
Dim temps() As Double = {18.5, 21, 19.25}

For i As Integer = 0 To temps.Length - 1
    Console.WriteLine($"Day {i + 1}: {temps(i)}")
Next

Dim sum As Double = 0
For Each t As Double In temps
    sum += t
Next
Console.WriteLine($"Average: {sum / temps.Length:F2}")     ' 19.58

Use For Each when you only read, and an index loop when you need the position or want to assign.

Resizing: ReDim and Preserve

A .NET array's size never changes, but ReDim creates a new array and points your variable at it. Without Preserve the old values are lost:

VB
Dim a() As Integer = {1, 2, 3}
ReDim Preserve a(4)       ' new upper bound 4: a = {1, 2, 3, 0, 0}
a(3) = 4
a(4) = 5
ReDim a(1)                ' no Preserve: a = {0, 0}

Each ReDim Preserve copies the whole array, so doing it in a loop is slow. When the size changes often, use a List(Of T) (see Collections and LINQ). Array.Resize(a, newLength) does the same job with a length instead of an upper bound.

Multidimensional and jagged arrays

A rectangular array has fixed rows and columns, declared with a comma:

VB
Dim board(2, 2) As Char                  ' 3 x 3
board(1, 1) = "X"c

Dim table(,) As Integer = {{1, 2, 3}, {4, 5, 6}}
Console.WriteLine(table(1, 2))                 ' 6
Console.WriteLine(table.GetLength(0))          ' 2 rows
Console.WriteLine(table.GetLength(1))          ' 3 columns

A jagged array is an array of arrays, so rows may have different lengths:

VB
Dim jag()() As Integer = New Integer(2)() {}
jag(0) = {1}
jag(1) = {1, 2}
jag(2) = {1, 2, 3}
Console.WriteLine(jag(2)(1))                   ' 2

Rectangular arrays are compact and good for grids; jagged arrays save memory for uneven data and are usually faster in .NET.

C# Stand-in (C#): rectangular and jagged arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Sorting, searching and copying

The System.Array class has shared helpers. They work in place or return a position:

VB
Dim nums() As Integer = {42, 7, 19, 3}

Array.Sort(nums)                                 ' 3 7 19 42
Array.Reverse(nums)                              ' 42 19 7 3
Dim pos As Integer = Array.IndexOf(nums, 19)     ' 1 (or -1 if missing)
Dim copy() As Integer = CType(nums.Clone(), Integer())
Dim part(1) As Integer
Array.Copy(nums, 1, part, 0, 2)                  ' part = {19, 7}
Array.Clear(nums, 0, nums.Length)                ' all zeros

Dim sorted = Array.BinarySearch(New Integer() {3, 7, 19, 42}, 19)   ' 2 (array must be sorted)

LINQ adds more: nums.Max(), nums.Min(), nums.Sum(), nums.Average(), nums.OrderBy(Function(n) n), nums.Contains(7).

C# Stand-in (C#): Array helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Passing arrays to procedures

Arrays are references, so a ByVal parameter lets the procedure modify the elements but not replace the caller's array:

VB
Sub DoubleAll(values() As Integer)
    For i As Integer = 0 To values.Length - 1
        values(i) *= 2
    Next
End Sub

Function Largest(values() As Integer) As Integer
    Dim best = values(0)
    For Each v In values
        If v > best Then best = v
    Next
    Return best
End Function

Use ParamArray to accept a variable argument list, as shown in Subs and Functions.

Common mistakes

  • Treating Dim a(5) as five elements (it is six).
  • Looping For i = 0 To a.Length (one step too far).
  • Expecting b = a to copy the array.
  • Using ReDim without Preserve and losing data.
  • Calling BinarySearch on an unsorted array.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many elements does Dim a(9) As Integer create?

    The number is the upper bound; indexes 0 to 9 give ten elements.
  2. 2. What does ReDim Preserve a(4) do?

    Arrays cannot change size, so ReDim allocates a new one; Preserve copies the old elements.
  3. 3. After Dim b = a (both arrays), then b(0) = 99, what is a(0)?

    Both variables refer to the same array object.
  4. 4. What is a jagged array?

    Jagged arrays are declared with consecutive parentheses, e.g. Integer()(), and each row is its own array.
  5. 5. Which call finds the position of a value?

    Array.IndexOf returns the index of the first match or -1 when absent.

Summary

  • Dim a(n) declares upper bound n, so n + 1 elements; indexes start at 0 and Length gives the count.
  • Arrays are fixed-size reference types; ReDim Preserve creates a resized copy, so prefer List(Of T) for growth.
  • Multidimensional arrays use commas; jagged arrays use ()().
  • Array.Sort, Reverse, IndexOf, Copy, Clear and LINQ methods do the common work.
  • Pass arrays by value to let a procedure change elements; avoid off-by-one errors.

Next: Error Handling