Skip to main content This browser is no longer supported. Show
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Arrays in Visual Basic
In this articleAn 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 to use 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
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. Some quick examples before explanation:
Array elements in a simple arrayLet's create an array named The following
illustration shows the
The following example contains the Visual Basic code that creates and uses the array:
The example does three things:
The Creating an arrayYou can define the size of an array in several ways:
If you have an existing array, you can redefine its size by using the
For more information, see the ReDim Statement. Storing values in an arrayYou can access each location in an array by using an index of type The following example shows some statements that store and retrieve values in arrays.
Populating an array with array literalsBy using an array literal, you can populate an array with an initial set of values at the same time that you create it. An array literal consists of a list of comma-separated values that are enclosed in braces ( 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.
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 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 Note that the previous example defines 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.
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
For additional examples, see How to: Initialize an Array Variable in Visual Basic. Iterating through an arrayWhen you iterate through an array, you access each element in the array from the lowest index to the highest or from the highest to the lowest. Typically, use either the For...Next Statement or the For Each...Next Statement to iterate through the elements of an array. When you don't know the upper bounds of the array, you can call the Array.GetUpperBound method to get the highest value of the index. Although the lowest index value is almost always 0, you can call the Array.GetLowerBound method to get the lowest value of the index. The following example
iterates through a one-dimensional array by using the
The following example iterates through a multidimensional array by using a
The following example uses a For Each...Next Statementto iterate through a one-dimensional array and a two-dimensional array.
Array sizeThe 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 size is 16 (or (3 + 1) * (3 + 1).
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
There are several things to keep in mind when dealing with the size of an array.
The array typeEvery array has a data type, which differs from the data type of its elements. There is no single data type for all arrays. Instead, the data type of an array is 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
Also, the ReDim Statement cannot operate on a variable declared as type You can find out the data type of either an array or its elements in several ways.
The following example calls the both the
Arrays as return values and parametersTo return an array from a To specify an array as a parameter to a In the following example, the
In the following example, the
Jagged arraysSometimes 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.
The previous example assigns values to the jagged array on an element-by-element basis by using a
A jagged array is a one-dimensional array whose elements contain arrays. Therefore, the Array.Length property and the
Zero-length arraysVisual Basic differentiates between an uninitialized array (an array whose value is
A zero-length array is declared with a dimension of -1. For example:
You might need to create a zero-length array under the following circumstances:
Splitting an arrayIn 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. 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 most common criteria for splitting an array are:
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.)
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 arrays do not include the element that contains the delimiter.
Joining arraysYou can also combine a number of arrays into a single larger array. To do this, you also use the Array.Copy method.
Note 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:
The following example uses the second approach to add four arrays with ten elements each to a single array.
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.
Collections as an alternative to arraysArrays are most useful for creating
and working with a fixed number of strongly typed objects. Collections provide a more flexible way to work with groups of objects. Unlike arrays, which require that you explicitly change the size of an array with the When you use
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. For more information about collections, see Collections.
See also
FeedbackSubmit and view feedback for Additional resourcesAdditional resourcesIn this articleHow to store integer in array in Java?Syntax. int[][] intArray = new int[10][20]; //a 2D array or matrix.. int[][][] intArray = new int[10][20][10]; //a 3D array.. Which way we can look through a list of values stored in an array and find a particular piece of data?Searching for an Element
There are two ways we can search in an array, they are: Linear search. Binary search.
When you create a numeric array in C# what value are its elements set to by default?The default values of numeric array elements are set to zero, and reference elements are set to null . A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null .
How can we create an array of 10 integers?Array Initialization in Java
To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.
|