Arrays - Visual Basic - Microsoft Docs
Arrays - Visual Basic - Microsoft Docs
In this article
Array elements in a simple array
Creating an array
Storing values in an array
Populating an array with array literals
Iterating through an array
Array size
The array type
Arrays as return values and parameters
Jagged arrays
Zero-length arrays
Splitting an array
Joining arrays
Collections as an alternative to arrays
Related topics
See also
An array is a set of values, which are termed elements, that are logically related to
each other. For example, an array may consist of the number of students in each
grade in a grammar school; each element of the array is the number of students
in a single grade. Similarly, an array may consist of a student's grades for a class;
each element of the array is a single grade.
It is possible individual variables to store each of our data items. For example, if
our application analyzes student grades, we can use a separate variable for each
student's grade, such as englishGrade1 , englishGrade2 , etc. This approach has
three major limitations:
1 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
By using an array, you can refer to these related values by the same name, and
use a number that’s called an index or subscript to identify an individual element
based on its position in the array. The indexes of an array range from 0 to one
less than the total number of elements in the array. When you use Visual Basic
syntax to define the size of an array, you specify its highest index, not the total
number of elements in the array. You can work with the array as a unit, and the
ability to iterate its elements frees you from needing to know exactly how many
elements it contains at design time.
VB = Copy
2 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
' Redefine the size of an existing array and reset the values.
ReDim numbers(15)
The following illustration shows the students array. For each element of the
array:
3 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
The following example contains the Visual Basic code that creates and uses the
array:
VB = Copy
Module SimpleArray
Public Sub Main()
' Declare an array with 7 elements.
Dim students(6) As Integer
4 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
Creating an array
You can define the size of an array in several ways:
VB = Copy
You can use a New clause to supply the size of an array when it’s created:
VB = Copy
5 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
If you have an existing array, you can redefine its size by using the ReDim
statement. You can specify that the ReDim statement keep the values that are in
the array, or you can specify that it create an empty array. The following example
shows different uses of the ReDim statement to modify the size of an existing
array.
VB = Copy
' Assign a new array size and retain the current values.
ReDim Preserve cargoWeights(20)
' Assign a new array size and retain only the first five values.
ReDim Preserve cargoWeights(4)
' Assign a new array size and discard all current element val‐
ues.
ReDim cargoWeights(15)
The following example shows some statements that store and retrieve values in
arrays.
VB = Copy
6 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
Module Example
Public Sub Main()
' Create a 10-element integer array.
Dim numbers(9) As Integer
Dim value As Integer = 2
When you create an array by using an array literal, you can either supply the array
type or use type inference to determine the array type. The following example
shows both options.
VB = Copy
7 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
When you use type inference, the type of the array is determined by the
dominant type in the list of literal values. The dominant type is the type to which
all other types in the array can widen. If this unique type can’t be determined, the
dominant type is the unique type to which all other types in the array can narrow.
If neither of these unique types can be determined, the dominant type is Object .
For example, if the list of values that’s supplied to the array literal contains values
of type Integer , Long , and Double , the resulting array is of type Double .
Because Integer and Long widen only to Double , Double is the dominant type.
For more information, see Widening and Narrowing Conversions.
7 Note
You can use type inference only for arrays that are defined as local variables
in a type member. If an explicit type definition is absent, arrays defined with
array literals at the class level are of type Object[] . For more information,
see Local type inference.
Note that the previous example defines values as an array of type Double even
though all the array literals are of type Integer . You can create this array
because the values in the array literal can widen to Double values.
You can also create and populate a multidimensional array by using nested array
literals. Nested array literals must have a number of dimensions that’s consistent
with the resulting array. The following example creates a two-dimensional array
of integers by using nested array literals.
VB = Copy
8 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
When using nested array literals to create and populate an array, an error occurs
if the number of elements in the nested array literals don't match. An error also
occurs if you explicitly declare the array variable to have a different number of
dimensions than the array literals.
Just as you can for one-dimensional arrays, you can rely on type inference when
creating a multidimensional array with nested array literals. The inferred type is
the dominant type for all the values in all the array literals for all nesting level.
The following example creates a two-dimensional array of type Double[,] from
values that are of type Integer and Double .
VB = Copy
Dim arr = {{1, 2.0}, {3, 4}, {5, 6}, {7, 8}}
For additional examples, see How to: Initialize an Array Variable in Visual Basic.
VB = Copy
9 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
Module IterateArray
Public Sub Main()
Dim numbers = {10, 20, 30}
VB = Copy
Module IterateArray
Public Sub Main()
Dim numbers = {{1, 2}, {3, 4}, {5, 6}}
10 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
The following example uses a For Each...Next Statementto iterate through a one-
dimensional array and a two-dimensional array.
VB = Copy
Module IterateWithForEach
Public Sub Main()
' Declare and iterate through a one-dimensional array.
Dim numbers1 = {10, 20, 30}
Array size
The size of an array is the product of the lengths of all its dimensions. It
represents the total number of elements currently contained in the array. For
example, the following example declares a 2-dimensional array with four
elements in each dimension. As the output from the example shows, the array's
11 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
VB = Copy
Module Example
Public Sub Main()
Dim arr(3, 3) As Integer
Console.WriteLine(arr.Length)
End Sub
End Module
' The example displays the following output:
' 16
7 Note
This discussion of array size does not apply to jagged arrays. For information
on jagged arrays and determining the size of a jagged array, see the Jagged
arrays section.
You can find the size of an array by using the Array.Length property. You can find
the length of each dimension of a multidimensional array by using the
Array.GetLength method.
You can resize an array variable by assigning a new array object to it or by using
the ReDim Statement statement. The following example uses the ReDim
statement to change a 100-element array to a 51-element array.
VB = Copy
Module Example
Public Sub Main()
Dim arr(99) As Integer
Console.WriteLine(arr.Length)
Redim arr(50)
Console.WriteLine(arr.Length)
End Sub
12 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
End Module
' The example displays the following output:
' 100
' 51
There are several things to keep in mind when dealing with the size of an array.
Dimension The index of each dimension is 0-based, which means it ranges from
Length 0 to its upper bound. Therefore, the length of a given dimension is
one greater than the declared upper bound of that dimension.
Length Limits The length of every dimension of an array is limited to the maximum
value of the Integer data type, which is Int32.MaxValue or (2 ^ 31)
- 1. However, the total size of an array is also limited by the memory
available on your system. If you attempt to initialize an array that
exceeds the amount of available memory, the runtime throws an
OutOfMemoryException.
Size and An array's size is independent of the data type of its elements. The
Element Size size always represents the total number of elements, not the number
of bytes that they consume in memory.
13 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
determined by the number of dimensions, or rank, of the array, and the data type
of the elements in the array. Two array variables are of the same data type only
when they have the same rank and their elements have the same data type. The
lengths of the dimensions of an array do not influence the array data type.
Every array inherits from the System.Array class, and you can declare a variable to
be of type Array , but you cannot create an array of type Array . For example,
although the following code declares the arr variable to be of type Array and
calls the Array.CreateInstance method to instantiate the array, the array's type
proves to be Object[].
VB = Copy
Module Example
Public Sub Main()
Dim arr As Array = Array.CreateInstance(GetType(Object),
19)
Console.WriteLine(arr.Length)
Console.WriteLine(arr.GetType().Name)
End Sub
End Module
' The example displays the following output:
' 19
' Object[]
Also, the ReDim Statement 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.
You can find out the data type of either an array or its elements in several ways.
You can call the GetType method on the variable to get a Type object that
represents the run-time type of the variable. The Type object holds
extensive information in its properties and methods.
You can pass the variable to the TypeName function to get a String with
the name of run-time type.
14 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
The following example calls the both the GetType method and the TypeName
function to determine the type of an array. The array type is Byte(,) . Note that
the Type.BaseType property also indicates that the base type of the byte array is
the Array class.
VB = Copy
Module Example
Public Sub Main()
Dim bytes(9,9) As Byte
Console.WriteLine($"Type of {nameof(bytes)} array:
{bytes.GetType().Name}")
Console.WriteLine($"Base class of {nameof(bytes)}:
{bytes.GetType().BaseType.Name}")
Console.WriteLine()
Console.WriteLine($"Type of {nameof(bytes)} array:
{TypeName(bytes)}")
End Sub
End Module
' The example displays the following output:
' Type of bytes array: Byte[,]
' Base class of bytes: Array
'
' Type of bytes array: Byte(,)
15 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
number of dimensions.
VB = Copy
Module ReturnValuesAndParams
Public Sub Main()
Dim numbers As Integer() = GetNumbers()
ShowNumbers(numbers)
End Sub
VB = Copy
Module Example
Public Sub Main()
Dim numbers As Integer(,) = GetNumbersMultidim()
16 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
ShowNumbersMultidim(numbers)
End Sub
Jagged arrays
Sometimes the data structure in your application is two-dimensional but not
rectangular. For example, you might use an array to store data about the high
temperature of each day of the month. The first dimension of the array
represents the month, but the second dimension represents the number of days,
and the number of days in a month is not uniform. A jagged array, which is also
called an array of arrays, is designed for such scenarios. A jagged array is an array
whose elements are also arrays. A jagged array and each element in a jagged
array can have one or more dimensions.
The following example uses an array of months, each element of which is an array
of days. The example uses a jagged array because different months have different
numbers of days. The example shows how to create a jagged array, assign values
to it, and retrieve and display its values.
17 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
VB = Copy
Imports System.Globalization
Module JaggedArray
Public Sub Main()
' Declare the jagged array of 12 elements. Each element is
an array of Double.
Dim sales(11)() As Double
' Set each element of the sales array to a Double array of
the appropriate size.
For month As Integer = 0 To 11
' The number of days in the month determines the appro‐
priate size.
Dim daysInMonth As Integer =
DateTime.DaysInMonth(Year(Now), month + 1)
sales(month) = New Double(daysInMonth - 1) {}
Next
18 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
(dayInMonth),-5} ")
End If
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' Jan Feb Mar Apr May Jun Jul Aug
Sep Oct Nov Dec
' 1. 0 100 200 300 400 500 600 700
800 900 1000 1100
' 2. 1 101 201 301 401 501 601 701
801 901 1001 1101
' 3. 2 102 202 302 402 502 602 702
802 902 1002 1102
' 4. 3 103 203 303 403 503 603 703
803 903 1003 1103
' 5. 4 104 204 304 404 504 604 704
804 904 1004 1104
' 6. 5 105 205 305 405 505 605 705
805 905 1005 1105
' 7. 6 106 206 306 406 506 606 706
806 906 1006 1106
' 8. 7 107 207 307 407 507 607 707
807 907 1007 1107
' 9. 8 108 208 308 408 508 608 708
808 908 1008 1108
' 10. 9 109 209 309 409 509 609 709
809 909 1009 1109
' 11. 10 110 210 310 410 510 610 710
810 910 1010 1110
' 12. 11 111 211 311 411 511 611 711
811 911 1011 1111
' 13. 12 112 212 312 412 512 612 712
812 912 1012 1112
' 14. 13 113 213 313 413 513 613 713
813 913 1013 1113
' 15. 14 114 214 314 414 514 614 714
814 914 1014 1114
' 16. 15 115 215 315 415 515 615 715
815 915 1015 1115
' 17. 16 116 216 316 416 516 616 716
816 916 1016 1116
' 18. 17 117 217 317 417 517 617 717
817 917 1017 1117
19 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
VB = Copy
Module Example
Public Sub Main()
Dim values1d = { 1, 2, 3 }
20 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
VB = Copy
21 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
Module Example
Public Sub Main()
Dim jagged = { ({1, 2}), ({2, 3, 4}), ({5, 6}), ({7, 8, 9,
10}) }
Console.WriteLine($"The value of jagged.Length:
{jagged.Length}.")
Dim total = jagged.Length
For ctr As Integer = 0 To jagged.GetUpperBound(0)
Console.WriteLine($"Element {ctr + 1} has
{jagged(ctr).Length} elements.")
total += jagged(ctr).Length
Next
Console.WriteLine($"The total number of elements in the
jagged array: {total}")
End Sub
End Module
' The example displays the following output:
' The value of jagged.Length: 4.
' Element 1 has 2 elements.
' Element 2 has 3 elements.
' Element 3 has 2 elements.
' Element 4 has 4 elements.
' The total number of elements in the jagged array: 15
Zero-length arrays
Visual Basic differentiates between a uninitialized array (an array whose value is
Nothing ) and a zero-length array or empty array (an array that has no elements.)
An uninitialized array is one that has not been dimensioned or had any values
assigned to it. For example:
VB = Copy
22 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
VB = Copy
You might need to create a zero-length array under the following circumstances:
You want to keep your code simple by not having to check for Nothing as a
special case.
Splitting an array
In some cases, you may need to split a single array into multiple arrays. This
involves identifying the point or points at which the array is to be split, and then
spitting the array into two or more separate arrays.
7 Note
This section does not discuss splitting a single string into a string array
based on some delimiter. For information on splitting a string, see the
String.Split method.
The number of elements in the array. For example, you might want to split
an array of more than a specified number of elements into a number of
approximately equal parts. For this purpose, you can use the value returned
by either the Array.Length or Array.GetLength method.
23 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
Once you've determined the index or indexes at which the array should be split,
you can then create the individual arrays by calling the Array.Copy method.
The following example splits an array into two arrays of approximately equal size.
(If the total number of array elements is odd, the first array has one more element
than the second.)
VB = Copy
Module Example
Public Sub Main()
' Create an array of 100 elements.
Dim arr(99) As Integer
' Populate the array.
Dim rnd As new Random()
For ctr = 0 To arr.GetUpperBound(0)
arr(ctr) = rnd.Next()
Next
The following example splits a string array into two arrays based on the presence
of an element whose value is "zzz", which serves as the array delimiter. The new
24 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
VB = Copy
Module Example
Public Sub Main()
Dim rnd As New Random()
Joining arrays
You can also combine a number of arrays into a single larger array. To do this,
you also use the Array.Copy method.
7 Note
25 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
This section does not discuss joining a string array into a single string. For
information on joining a string array, see the String.Join method.
Before copying the elements of each array into the new array, you must first
ensure that you have initialized the array so that it is large enough to
accommodate the new array. You can do this in one of two ways:
Use the ReDim Preserve statement to dynamically expand the array before
adding new elements to it. This is the easiest technique, but it can result in
performance degradation and excessive memory consumption when you
are copying large arrays.
Calculate the total number of elements needed for the new large array, then
add the elements of each source array to it.
The following example uses the second approach to add four arrays with ten
elements each to a single array.
VB = Copy
Imports System.Collections.Generic
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim tasks As New List(Of Task(Of Integer()))
' Generate four arrays.
For ctr = 0 To 3
Dim value = ctr
tasks.Add(Task.Run(Function()
Dim arr(9) As Integer
For ndx = 0 To
arr.GetUpperBound(0)
arr(ndx) = value
Next
Return arr
End Function))
Next
Task.WaitAll(tasks.ToArray())
' Compute the number of elements in all arrays.
Dim elements = 0
For Each task In tasks
26 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
elements += task.Result.Length
Next
Dim newArray(elements - 1) As Integer
Dim index = 0
For Each task In tasks
Dim n = task.Result.Length
Array.Copy(task.Result, 0, newArray, index, n)
index += n
Next
Console.WriteLine($"The new array has {newArray.Length}
elements.")
End Sub
End Module
' The example displays the following output:
' The new array has 40 elements.
Since in this case the source arrays are all small, we can also dynamically expand
the array as we add the elements of each new array to it. The following example
does that.
VB = Copy
Imports System.Collections.Generic
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim tasks As New List(Of Task(Of Integer()))
' Generate four arrays.
For ctr = 0 To 3
Dim value = ctr
tasks.Add(Task.Run(Function()
Dim arr(9) As Integer
For ndx = 0 To
arr.GetUpperBound(0)
arr(ndx) = value
Next
Return arr
End Function))
Next
Task.WaitAll(tasks.ToArray())
27 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
When you use ReDim to redimension an array, Visual Basic creates a new array
and releases the previous one. This takes execution time. Therefore, if the number
of items you are working with changes frequently, or you cannot predict the
maximum number of items you need, you'll usually obtain better performance by
using a collection.
For some collections, you can assign a key to any object that you put into the
collection so that you can quickly retrieve the object by using the key.
If your collection contains elements of only one data type, you can use one of the
classes in the System.Collections.Generic namespace. A generic collection
enforces type safety so that no other data type can be added to it.
28 de 29 8/15/20 8:40 a. m.
Arrays - Visual Basic | Microsoft Docs https://docs.microsoft.com/en-us/dotnet/visual-basic/programmi...
Related topics
Term Definition
How to: Initialize an Array Variable Describes how to populate arrays with initial
in Visual Basic values.
How to: Sort An Array in Visual Shows how to sort the elements of an array
Basic alphabetically.
How to: Assign One Array to Describes the rules and steps for assigning an
Another Array array to another array variable.
See also
System.Array
Dim Statement
ReDim Statement
# Yes $ No
29 de 29 8/15/20 8:40 a. m.