|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
Overview of Arrays in Visual Basic
An array is a set of values that are logically related to each other, such as the number of students in each grade in a grammar school.
An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell them apart. The individual values are called the elements of the array. They are contiguous from index 0 through the highest index value.
The following example declares an array variable to hold the number of students in each grade in a grammar school.
Dim students(6) As Integer
The array students in the preceding example contains 7 elements. The indexes of the elements range from 0 through 6. Having this array is simpler than declaring 7 different variables.
The following illustration shows the array students. For each element of the array:
The index of the element represents the grade (index 0 represents kindergarten).
The value contained in the element represents the number of students in that grade.
The following example shows how to refer to the first, second, and last element of the array students.
Dim kindergarten As Integer = students(0) Dim firstGrade As Integer = students(1) Dim sixthGrade As Integer = students(6) MsgBox("Students in kindergarten = " & CStr(kindergarten)) MsgBox("Students in first grade = " & CStr(firstGrade)) MsgBox("Students in sixth grade = " & CStr(sixthGrade))
You can refer to the array as a whole by using just the array variable name without indexes.
Array Types and Other Types
Every array has a data type, but it is not the same as the data type of its elements. For example, the array students in the preceding example is of type Integer(), while each of its elements is of type Integer. The notation Integer() means an array of Integer elements. For more information, see.
Every array inherits from theclass, and you can declare a variable to be of type Array, but you cannot create an array of type Array. Also, the cannot operate on a variable declared as type Array. For these reasons, and for type safety, it is advisable to declare every array as a specific type, such as Integer in the preceding example.
The array students in the preceding example uses one index and is said to be one-dimensional. An array that uses more than one index or subscript is called multidimensional.
Another kind of array is one which holds other arrays as elements. This is known as an array of arrays or a jagged array. A jagged array can be either one-dimensional or multidimensional, and so can its elements.
In contrast to an array, a variable containing a single value is called a scalar variable.
An array is not the same as a collection. For more information, see.