Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Array Declaration
  VB.NET Array Dimensions
 Working with Dimensions
  One Dimension
  Two Dimensions
  Three Dimensions
  More than Three Dimensions
 Using Different Dimensions
 See also
  How to: Initialize an Array Variable in Visual Basic
  To initialize an array variable by using an array literal
  To initialize a multidimensional array variable by using array literals
  To initialize a jagged array variable by using array literals
 See also
  How to: Sort An Array in Visual Basic
 Example
 Compiling the Code
 Robust Programming
 See also
  How to: Assign One Array to Another Array
  To assign one array to another array
 See also
  Source/Reference

VB.NET Array Declaration

VB.NET Array Dimensions

A dimension is a direction in which you can vary the specification of an array's elements. An array that holds the sales total for each day of the month has one dimension (the day of the month). An array that holds the sales total by department for each day of the month has two dimensions (the department number and the day of the month). The number of dimensions an array has is called its rank.

Note

You can use the Rank property to determine the how many dimensions an array has.

Working with Dimensions

You specify an element of an array by supplying an index or subscript for each of its dimensions. The elements are contiguous along each dimension from index 0 through the highest index for that dimension.

The following illustrations show the conceptual structure of arrays with different ranks. Each element in the illustrations shows the index values that access it. For example, you can access the first element of the second row of the two-dimensional array by specifying indexes (1, 0).

Diagram that shows a one-dimensional array.

Diagram that shows a two-dimensional array.

Diagram that shows a three-dimensional array.

One Dimension

Many arrays have only one dimension, such as the number of people of each age. The only requirement to specify an element is the age for which that element holds the count. Therefore, such an array uses only one index. The following example declares a variable to hold a one-dimensional array of age counts for ages 0 through 120.

VB
Dim ageCounts(120) As UInteger

Two Dimensions

Some arrays have two dimensions, such as the number of offices on each floor of each building on a campus. The specification of an element requires both the building number and the floor, and each element holds the count for that combination of building and floor. Therefore, such an array uses two indexes. The following example declares a variable to hold a two-dimensional array of office counts, for buildings 0 through 40 and floors 0 through 5.

VB
Dim officeCounts(40, 5) As Byte

A two-dimensional array is also called a rectangular array.

Three Dimensions

A few arrays have three dimensions, such as values in three-dimensional space. Such an array uses three indexes, which in this case represent the x, y, and z coordinates of physical space. The following example declares a variable to hold a three-dimensional array of air temperatures at various points in a three-dimensional volume.

VB
Dim airTemperatures(99, 99, 24) As Single

More than Three Dimensions

Although an array can have as many as 32 dimensions, it is rare to have more than three.

Note

When you add dimensions to an array, the total storage needed by the array increases considerably, so use multidimensional arrays with care.

Using Different Dimensions

Suppose you want to track sales amounts for every day of the present month. You might declare a one-dimensional array with 31 elements, one for each day of the month, as the following example shows.

VB
Dim salesAmounts(30) As Double

Now suppose you want to track the same information not only for every day of a month but also for every month of the year. You might declare a two-dimensional array with 12 rows (for the months) and 31 columns (for the days), as the following example shows.

VB
Dim salesAmounts(11, 30) As Double

Now suppose you decide to have your array hold information for more than one year. If you want to track sales amounts for 5 years, you could declare a three-dimensional array with 5 layers, 12 rows, and 31 columns, as the following example shows.

VB
Dim salesAmounts(4, 11, 30) As Double

Note that, because each index varies from 0 to its maximum, each dimension of salesAmounts is declared as one less than the required length for that dimension. Note also that the size of the array increases with each new dimension. The three sizes in the preceding examples are 31, 372, and 1,860 elements respectively.

Note

You can create an array without using the Dim statement or the New clause. For example, you can call the CreateInstance method, or another component can pass your code an array created in this manner. Such an array can have a lower bound other than 0. You can always test for the lower bound of a dimension by using the GetLowerBound method or the LBound function.

See also

How to: Initialize an Array Variable in Visual Basic

You initialize an array variable by including an array literal in a New clause and specifying the initial values of the array. You can either specify the type or allow it to be inferred from the values in the array literal. For more information about how the type is inferred, see "Populating an Array with Initial Values" in Arrays.

To initialize an array variable by using an array literal

  • Either in the New clause, or when you assign the array value, supply the element values inside braces ({}). The following example shows several ways to declare, create, and initialize a variable to contain an array that has elements of type Char.

    VB
  • ' The following five lines of code create the same array.
    ' Preferred syntaxes are on the lines with chars1 and chars2.
    Dim chars1 = {"%"c, "&"c, "@"c}
    Dim chars2 As Char() = {"%"c, "&"c, "@"c}
    
    Dim chars3() As Char = {"%"c, "&"c, "@"c}
    Dim chars4 As Char() = New Char(2) {"%"c, "&"c, "@"c}
    Dim chars5() As Char = New Char(2) {"%"c, "&"c, "@"c}
    

    After each statement executes, the array that's created has a length of 3, with elements at index 0 through index 2 containing the initial values. If you supply both the upper bound and the values, you must include a value for every element from index 0 through the upper bound.

    Notice that you do not have to specify the index upper bound if you supply element values in an array literal. If no upper bound is specified, the size of the array is inferred based on the number of values in the array literal.

To initialize a multidimensional array variable by using array literals

  • Nest values inside braces ({}) within braces. Ensure that the nested array literals all infer as arrays of the same type and length. The following code example shows several examples of multidimensional array initialization.

    VB
    Dim numbers = {{1, 2}, {3, 4}, {5, 6}}
    Dim customerData = {{"City Power & Light", "http://www.cpandl.com/"},
                        {"Wide World Importers", "http://wideworldimporters.com"},
                        {"Lucerne Publishing", "http://www.lucernepublishing.com"}}
    
    ' You can nest array literals to create arrays that have more than two 
    ' dimensions.
    Dim twoSidedCube = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
    
  • You can explicitly specify the array bounds, or leave them out and have the compiler infer the array bounds based on the values in the array literal. If you supply both the upper bounds and the values, you must include a value for every element from index 0 through the upper bound in every dimension. The following example shows several ways to declare, create, and initialize a variable to contain a two-dimensional array that has elements of type Short

    VB
    ' The following five lines of code create the same array.
    ' Preferred syntaxes are on the lines with scores1 and scores2.
    Dim scores1 = {{10S, 10S, 10S}, {10S, 10S, 10S}}
    Dim scores2 As Short(,) = {{10, 10, 10}, {10, 10, 10}}
    
    Dim scores3(,) As Short = {{10, 10, 10}, {10, 10, 10}}
    Dim scores4 As Short(,) = New Short(1, 2) {{10, 10, 10}, {10, 10, 10}}
    Dim scores5(,) As Short = New Short(1, 2) {{10, 10, 10}, {10, 10, 10}}
    

    After each statement executes, the created array contains six initialized elements that have indexes (0,0), (0,1), (0,2), (1,0), (1,1), and (1,2). Each array location contains the value 10.

  • The following example iterates through a multidimensional array. In a Windows console application that is written in Visual Basic, paste the code inside the Sub Main() method. The last comments show the output.

    VB
    Dim numbers = {{1, 2}, {3, 4}, {5, 6}}
    
    ' Iterate through the array.
    For index0 = 0 To numbers.GetUpperBound(0)
        For index1 = 0 To numbers.GetUpperBound(1)
            Debug.Write(numbers(index0, index1).ToString & " ")
        Next
        Debug.WriteLine("")
    Next
    ' Output
    '  1 2
    '  3 4
    '  5 6
    

To initialize a jagged array variable by using array literals

  • Nest object values inside braces ({}). Although you can also nest array literals that specify arrays of different lengths, in the case of a jagged array, make sure that the nested array literals are enclosed in parentheses (()). The parentheses force the evaluation of the nested array literals, and the resulting arrays are used as the initial values of the jagged array. The following code example shows two examples of jagged array initialization.

    VB
    ' Create a jagged array of arrays that have different lengths.
    Dim jaggedNumbers = {({1, 2, 3}), ({4, 5}), ({6}), ({7})}
    
    ' Create a jagged array of Byte arrays.
    Dim images = {New Byte() {}, New Byte() {}, New Byte() {}}
    
  • The following example iterates through a jagged array. In a Windows console application that is written in Visual Basic, paste the code inside the Sub Main() method. The last comments in the code show the output.

    VB
    ' Create a jagged array of arrays that have different lengths.
    Dim jaggedNumbers = {({1, 2, 3}), ({4, 5}), ({6}), ({7})}
    
    For indexA = 0 To jaggedNumbers.Length - 1
        For indexB = 0 To jaggedNumbers(indexA).Length - 1
            Debug.Write(jaggedNumbers(indexA)(indexB) & " ")
        Next
        Debug.WriteLine("")
    Next
    
    ' Output:
    '  1 2 3 
    '  4 5 
    '  6
    '  7
    

See also

How to: Sort An Array in Visual Basic

This example declares an array of String objects named zooAnimals, populates it, and then sorts it alphabetically.

Example

Private Sub sortAnimals()  
    Dim zooAnimals(2) As String  
    zooAnimals(0) = "lion"  
    zooAnimals(1) = "turtle"  
    zooAnimals(2) = "ostrich"  
    Array.Sort(zooAnimals)  
End Sub  

Compiling the Code

This example requires:

  • Access to the System namespace.

Robust Programming

The following conditions may cause an exception:

See also

How to: Assign One Array to Another Array

Because arrays are objects, you can use them in assignment statements like other object types. An array variable holds a pointer to the data constituting the array elements and the rank and length information, and an assignment copies only this pointer.

To assign one array to another array

  1. Ensure that the two arrays have the same rank (number of dimensions) and compatible element data types.

  2. Use a standard assignment statement to assign the source array to the destination array. Do not follow either array name with parentheses.

    VB
  1. Dim formArray() As System.Windows.Forms.Form
    Dim controlArray() As System.Windows.Forms.Control
    controlArray = formArray
    

When you assign one array to another, the following rules apply:

  • Equal Ranks. The rank (number of dimensions) of the destination array must be the same as that of the source array.

    Provided the ranks of the two arrays are equal, the dimensions do not need to be equal. The number of elements in a given dimension can change during assignment.

  • Element Types. Either both arrays must have reference type elements or both arrays must have value type elements. For more information, see Value Types and Reference Types.

    • If both arrays have value type elements, the element data types must be exactly the same. The only exception to this is that you can assign an array of Enum elements to an array of the base type of that Enum.

    • If both arrays have reference type elements, the source element type must derive from the destination element type. When this is the case, the two arrays have the same inheritance relationship as their elements. This is called array covariance.

The compiler reports an error if the above rules are violated, for example if the data types are not compatible or the ranks are unequal. You can add error handling to your code to make sure that the arrays are compatible before attempting an assignment. You can also use the TryCast Operator keyword if you want to avoid throwing an exception.

See also

Source/Reference


©sideway

ID: 200900012 Last Updated: 9/12/2020 Revision: 0 Ref:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019