VB.NET Arrays

Arrays are fundamental data structures in VB.NET that allow you to store a collection of elements of the same data type under a single variable name. They are zero-indexed, meaning the first element is at index 0.

Types of Arrays

VB.NET supports several types of arrays:

1. Single-Dimensional Arrays

These are the most common type, representing a linear collection of elements.

Declaring and Initializing Single-Dimensional Arrays

Example 1: Declaring an array

Dim numbers(9) As Integer  ' Declares an array of 10 integers (indices 0 to 9)

Example 2: Declaring and initializing an array

Dim names() As String = {"Alice", "Bob", "Charlie"} ' Array size is determined by initializer

Example 3: Accessing array elements

numbers(0) = 10
Console.WriteLine(names(1)) ' Output: Bob

2. Multidimensional Arrays

These arrays represent data in more than one dimension, such as a grid or a cube.

Declaring and Initializing Multidimensional Arrays

You can declare arrays with multiple dimensions using commas within the parentheses.

Example 4: Two-dimensional array (matrix)

Dim matrix(2, 3) As Double ' A 3x4 matrix (indices 0-2 for first dim, 0-3 for second)
matrix(0, 0) = 1.1
matrix(1, 2) = 2.2

Example 5: Initializing a multidimensional array

Dim scores(,) As Integer = {{90, 85}, {78, 92}, {88, 76}}

3. Jagged Arrays

Jagged arrays are arrays of arrays. Each inner array can have a different size.

Declaring and Initializing Jagged Arrays

Jagged arrays are declared with separate sets of parentheses for each dimension.

Example 6: Jagged array

Dim jaggedArray(2)() As Integer ' An array that holds 3 inner arrays
jaggedArray(0) = New Integer() {1, 2, 3}
jaggedArray(1) = New Integer() {4, 5}
jaggedArray(2) = New Integer() {6, 7, 8, 9}

Console.WriteLine(jaggedArray(0)(2)) ' Output: 3
Console.WriteLine(jaggedArray(2)(3)) ' Output: 9

Array Properties and Methods

Arrays have useful properties and methods:

Example 7: Using array properties and methods

Dim numbers() As Integer = {5, 2, 8, 1, 9}
Console.WriteLine("Length: " & numbers.Length) ' Output: Length: 5

Array.Sort(numbers)
Console.WriteLine("Sorted: " & String.Join(", ", numbers)) ' Output: Sorted: 1, 2, 5, 8, 9

Array.Reverse(numbers)
Console.WriteLine("Reversed: " & String.Join(", ", numbers)) ' Output: Reversed: 9, 8, 5, 2, 1

Dim matrix(,) As Integer = {{1, 2}, {3, 4}}
Console.WriteLine("Rank: " & matrix.Rank) ' Output: Rank: 2
Console.WriteLine("Length of dimension 0: " & matrix.GetLength(0)) ' Output: Length of dimension 0: 2
Console.WriteLine("Length of dimension 1: " & matrix.GetLength(1)) ' Output: Length of dimension 1: 2

Iterating Through Arrays

The For Each loop is a convenient way to iterate through all elements of an array.

Example 8: Iterating with For Each

Dim fruits() As String = {"Apple", "Banana", "Cherry"}
For Each fruit As String In fruits
    Console.WriteLine(fruit)
Next
' Output:
' Apple
' Banana
' Cherry