Visual Basic .NET - Arrays

In VB.NET, an array is a collection of similar data types. It allows you to store multiple values of the same data type in a single variable. You can declare an array using the Dim keyword, followed by the name of the array, the size of the array, and the data type of the elements.

For example, to declare an array of integers with a size of 5, you would use the following code:

Dim myArray(4) As Integer

This creates an array called "myArray" with 5 elements, numbered 0 to 4.

You can then access individual elements of the array using their index, like this:

myArray(0) = 10
myArray(1) = 20
myArray(2) = 30
myArray(3) = 40
myArray(4) = 50

This sets the first element to 10, the second element to 20, and so on.

VB.NET provides several built-in functions and methods for working with arrays. Some of the most commonly used functions and methods include:

In VB.NET, a two-dimensional array is a collection of data elements organized in rows and columns. Each element is identified by a pair of indexes, one for the row and another for the column. The syntax for declaring a two-dimensional array is as follows:

Dim arr(,) As DataType = New DataType(rowSize, columnSize) {}

Here, DataType represents the data type of the elements in the array, rowSize represents the number of rows, and columnSize represents the number of columns.

To initialize a two-dimensional array with values, we can use nested loops as shown in the following example:

Dim arr(3, 3) As Integer ' declaring a 2D array with 4 rows and 4 columns
' initializing the array with values
For i As Integer = 0 To arr.GetUpperBound(0)
    For j As Integer = 0 To arr.GetUpperBound(1)
        arr(i, j) = i + j ' setting the element value
    Next
Next

In the above example, we have declared a two-dimensional array with 4 rows and 4 columns and initialized it with values using a nested loop. The GetUpperBound method is used to get the maximum index value for each dimension of the array.

We can also access and modify individual elements of a two-dimensional array using the row and column index. For example:

Dim arr(1, 1) As Integer ' declaring a 2D array with 2 rows and 2 columns
' initializing the array with values
arr(0, 0) = 1
arr(0, 1) = 2
arr(1, 0) = 3
arr(1, 1) = 4
' accessing and modifying the elements
Dim x As Integer = arr(0, 1) ' accessing the element at row 0 and column 1
arr(1, 1) = 5 ' modifying the element at row 1 and column 1

In the above example, we have declared a two-dimensional array with 2 rows and 2 columns and initialized it with values. We have also demonstrated how to access and modify individual elements using the row and column index.