Mastering Arrays: Your Ultimate Guide to Achieve Perfect Data Organization (VB.NET 2023)

Arrays - new 2023 - topbar

Introduction to VB.NET Arrays

An array is a collection of values of the same data type. In VB.NET, arrays can be used to store a group of values of the same type, such as integers, strings, or objects. Arrays provide a way to access and manipulate data more efficiently than individual variables.
There are several types of arrays in VB.NET, including one-dimensional arrays, multidimensional arrays, jagged arrays, and dynamic arrays. Each type of array has its own unique characteristics and is suitable for different situations.

One-Dimensional Arrays

A one-dimensional array is a collection of values of the same data type that are stored in a single row or column. One-dimensional arrays are the simplest type of array and are often used to store a list of values.

Declaring One-Dimensional Arrays

To declare a one-dimensional array in VB.NET, you need to specify the data type of the elements in the array and the size of the array. The following code declares a one-dimensional array of integers with a size of 5:

Dim numbers(4) As Integer

This creates an array named numbers with five elements, numbered 0 to 4.

Initializing One-Dimensional Arrays

You can initialize the values in a one-dimensional array when you declare the array. The following code initializes the numbers array with the values 1, 2, 3, 4, and 5:

Dim numbers() As Integer = {1, 2, 3, 4, 5}
Accessing Elements in One-Dimensional Arrays

You can access the elements in a one-dimensional array using an index value. The index value is the position of the element in the array, starting with 0. The following code accesses the first element in the numbers array:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim numbers() As Integer = {1, 2, 3, 4, 5}
        Dim a As Short = 0
        For a = 0 To 4
            ListBox1.Items.Add(numbers(a))
        Next
    End Sub

Run the app. It will give you the following output:

one-dimensional array1
More examples in One-Dimensional Arrays

Here’s an another example of how to declare and initialize a one-dimensional array in VB.NET:

Dim numbers(4) As Integer
numbers(0) = 10
numbers(1) = 20
numbers(2) = 30
numbers(3) = 40
numbers(4) = 50

In this example, we declare a one-dimensional array called numbers that can hold up to 5 integers (indexed from 0 to 4). We then assign values to each element of the array using the index number.
You can also declare and initialize a one-dimensional array in a single line of code using the New keyword:

Dim numbers() As Integer = New Integer() {10, 20, 30, 40, 50}

This code does the same thing as the previous example but in a more compact way.
You can access the elements of a one-dimensional array using their index number. Here’s an example:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim numbers() As Integer = New Integer() {10, 20, 30, 40, 50}
        ListBox1.Items.Add(numbers(0))
        ListBox1.Items.Add(numbers(1))
        ListBox1.Items.Add(numbers(2))
        ListBox1.Items.Add(numbers(3))
        ListBox1.Items.Add(numbers(4))

    End Sub
End Class

In this example, we access the first and fourth elements of the numbers array using their index numbers.
You can also use loops to iterate over the elements of a one-dimensional array. Here’s an example of how to use a For loop to print all the elements of the numbers array:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim numbers() As Integer = New Integer() {10, 20, 30, 40, 50}

        For i As Integer = 0 To numbers.Length - 1
            ListBox1.Items.Add(numbers(i))
        Next

    End Sub
End Class

You can also use a For Each loop to iterate over the elements of a one-dimensional array:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim numbers() As Integer = New Integer() {10, 20, 30, 40, 50}
        For Each number As Integer In numbers
            ListBox1.Items.Add(number)
        Next

    End Sub
End Class

All the above three examples will give the same output as shown below:

one-dimensional array2

In addition to integer arrays, you can also create one-dimensional arrays of other data types such as strings, doubles, booleans, and more. Here’s an example of how to declare and initialize a string array:

Dim names() As String = New String() {"John", "Mary", "Tom", "Sarah", "Mike"}

You can also create and manipulate arrays of user-defined types. Here’s an example of how to create a one-dimensional array of a custom Person class:

Public Class Form1
    Public Class Person
        Public Property Name As String
        Public Property Age As Integer
    End Class

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim people(2) As Person

        'Adding people to the array
        people(0) = New Person With {.Name = "John", .Age = 30}
        people(1) = New Person With {.Name = "Mary", .Age = 25}
        people(2) = New Person With {.Name = "Bob", .Age = 40}


        For Each person As Person In people
            ListBox1.Items.Add("Name: " & person.Name & ", Age: " & person.Age)
        Next
    End Sub
End Class

Run your app and check the output as given below:

one-dimensional array3

In this example, we first define a Person class with two properties: Name and Age. We then declare an array called people with three elements of type Person using Dim people(2) As Person.
We then add three instances of Person to the array using the index notation people(0), people(1), and people(2). Finally, we loop through the array and print the contents using the ListBox1.Items.Add statement.
You can modify the code to add more elements to the array or to modify the properties of the Person objects.

One-dimensional arrays are an essential part of programming in VB.NET, as they provide a way to store and manipulate collections of data efficiently. With the examples provided above, you should have a good understanding of how to declare, initialize, and manipulate one-dimensional arrays in VB.NET.

Multidimensional Arrays

A multidimensional array is an array that contains one or more arrays. Multidimensional arrays are often used to store data in a tabular format, such as a grid or a matrix.

Declaring Multidimensional Arrays

To declare a multidimensional array in VB.NET, you need to specify the data type of the elements in the array and the size of each dimension. The following code declares a two-dimensional array of integers with a size of 3 rows and 4 columns:

Dim matrix(2, 3) As Integer

This creates an array named matrix with 3 rows and 4 columns.

Initializing Multidimensional Arrays

You can initialize the values in a multidimensional array when you declare the array. The following code initializes the matrix array with the values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, and 12:

Accessing Elements in Multidimensional Arrays

You can access the elements in a multidimensional array using two index values. The first index value is the row number, and the second index value is the column number. The following code accesses the element in the second row and third column of the matrix array:

Dim element As Integer = matrix(1, 2)
More examples in Multidimensional Arrays

Here’s an another example of how to declare and initialize a multidimensional array in VB.NET:

To declare a two-dimensional array with three rows and four columns, you would write:

Dim matrix(2, 3) As Integer

In this case, the first dimension has a length of 2, and the second dimension has a length of 3. You can also declare a multidimensional array with more than two dimensions, such as a three-dimensional array:

Dim cube(2, 3, 4) As Integer

In this case, the array has three dimensions, with lengths of 2, 3, and 4.

To initialize a multidimensional array, you can use nested loops to assign values to each element. Here’s an example of how to initialize a two-dimensional array with some values:

Dim matrix(2, 3) As Integer

For i As Integer = 0 To 2
    For j As Integer = 0 To 3
        matrix(i, j) = i + j
    Next
Next

In this example, we use two nested For loops to assign values to each element of the matrix array. The value of each element is the sum of its row index i and column index j.
You can also initialize a multidimensional array using an array literal, as in the following example:

Dim matrix As Integer(,) = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

This creates a two-dimensional array with three rows and three columns, initialized with the specified values.
To access individual elements of a multidimensional array, you use multiple indexes separated by commas. For example, to access the element in the second row and third column of a two-dimensional array matrix, you would write:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim matrix As Integer(,) = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

        ' Loop through the matrix and add each element to the list
        For i As Integer = 0 To matrix.GetLength(0) - 1
            Dim row As String = ""
            For j As Integer = 0 To matrix.GetLength(1) - 1
                row += matrix(i, j).ToString() + " "
            Next
            ListBox1.Items.Add(row.TrimEnd())
        Next
    End Sub
End Class

Run the app and check the output:

one-dimensional array4

Here, we use nested For loops to loop through the matrix. For each row of the matrix, we create a string variable called row and concatenate each element of the row to it, separated by a space.
After the inner loop completes, we add the row string to the ListBox using the Items.Add method. The TrimEnd method is used to remove any trailing spaces at the end of the string.
This code will display the matrix in a listbox in a matrix form, with each row of the matrix displayed on a separate line in the listbox.

Jagged Arrays

A jagged array is an array of arrays, where each array can have a different size. Jagged arrays are often used to store data that is not rectangular in shape.

Declaring Jagged Arrays

To declare a jagged array in VB.NET, you need to specify the data type of the elements in the array and the size of the outer array. The following code declares a jagged array of integers with a size of 3:

Dim jaggedArray(2)() As Integer

This creates an array named jaggedArray with 3 elements.

Initializing Jagged Arrays

You can initialize the arrays in a jagged array when you declare the array. The following code initializes the jaggedArray array with three arrays of different sizes:

Dim jaggedArray()() As Integer = {New Integer() {1, 2}, New Integer() {3, 4, 5}, New Integer() {6, 7, 8, 9}}
Accessing Elements in Jagged Arrays

You can access the elements in a jagged array using two index values. The first index value is the index of the array in the outer array, and the second index value is the index of the element in the inner array. The following code accesses the element in the second array and third element of the jaggedArray array:

Dim element As Integer = jaggedArray(1)(2)
More examples in jagged arrays

here’s a more detailed example of jagged arrays in vb.net with outputs:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim jaggedArray As Integer()() = New Integer(2)() {}
        jaggedArray(0) = New Integer() {1, 2, 3}
        jaggedArray(1) = New Integer() {4, 5}
        jaggedArray(2) = New Integer() {6, 7, 8, 9}


        For i As Integer = 0 To jaggedArray.Length - 1
            Dim row As String = ""
            For j As Integer = 0 To jaggedArray(i).Length - 1
                row += jaggedArray(i)(j) & " "
                'ListBox1.Items.Add(jaggedArray(i)(j) & " ")
            Next
            ListBox1.Items.Add(row.TrimEnd())
        Next
    End Sub
End Class

Run the app and check the output:

one-dimensional array5

In this example, we create a jagged array with three sub-arrays, each with a different number of elements. We then print the contents of the jagged array using nested loops to iterate over each element of each sub-array.
Here’s another example that creates a jagged array using loops:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim jaggedArray As Integer()() = New Integer(3)() {}
        For i As Integer = 0 To jaggedArray.Length - 1
            jaggedArray(i) = New Integer(i + 1) {}
            For j As Integer = 0 To jaggedArray(i).Length - 1
                jaggedArray(i)(j) = i + j
            Next
        Next


        For i As Integer = 0 To jaggedArray.Length - 1
            Dim row As String = ""
            For j As Integer = 0 To jaggedArray(i).Length - 1
                row += jaggedArray(i)(j) & " "
                'ListBox1.Items.Add(jaggedArray(i)(j) & " ")
            Next
            ListBox1.Items.Add(row.TrimEnd())
        Next
    End Sub
End Class

The Output is given below:

one-dimensional array7

In this example, we create a jagged array with four sub-arrays, each with a different number of elements. We then initialize each element of the jagged array with the sum of its indexes, using nested loops to iterate over each element of each sub-array.
As you can see, jagged arrays allow you to store and manipulate data with varying sizes, which can be very useful in certain situations. However, they can be a bit trickier to work with than one-dimensional and multidimensional arrays, so it’s important to understand how they work and how to use them effectively.

Dynamic Arrays

Dynamic arrays are arrays that can change size at runtime. Dynamic arrays are useful when you don’t know the size of the array beforehand, or when you need to add or remove elements from the array.

Declaring Dynamic Arrays

To declare a dynamic array in VB.NET, you need to use the ReDim keyword. The following code declares a dynamic array of integers:

Dim dynamicArray() As Integer
Initializing Dynamic Arrays

You can initialize the values in a dynamic array after you declare the array. The following code initializes a dynamic array with the values 1, 2, 3, and 4:

ReDim dynamicArray(3)
dynamicArray(0) = 1
dynamicArray(1) = 2
dynamicArray(2) = 3
dynamicArray(3) = 4
Resizing Dynamic Arrays

You can resize a dynamic array using the ReDim keyword. The following code resizes the dynamicArray to have a size of 5:

ReDim Preserve dynamicArray(4)

Note that the Preserve keyword is used to preserve the existing values in the array. Without the Preserve keyword, the array would be resized and all existing values would be lost.

Adding Elements to Dynamic Arrays

You can add elements to a dynamic array using the ReDim keyword. The following code adds an element with the value 5 to the end of the dynamicArray:

ReDim Preserve dynamicArray(4)
dynamicArray(4) = 5
Removing Elements from Dynamic Arrays

You can remove elements from a dynamic array by resizing the array and leaving out the element that you want to remove. The following code removes the element at index 2 from the dynamicArray:

For i As Integer = 2 To dynamicArray.Length - 2
    dynamicArray(i) = dynamicArray(i + 1)
Next
ReDim Preserve dynamicArray(dynamicArray.Length - 2)
More examples in Dynamic Arrays

here’s an example of dynamic arrays in vb.net with outputs:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim dynamicArray As List(Of Integer) = New List(Of Integer)()

        'Adding elements to dynamic array
        dynamicArray.Add(1)
        dynamicArray.Add(2)
        dynamicArray.Add(3)
        dynamicArray.Add(4)

        'Printing elements of dynamic array
        Dim output As String = "Printing Dynamic Array" & Environment.NewLine
        For Each element As Integer In dynamicArray
            output += element & " "
        Next
        output += Environment.NewLine

        'Removing elements from dynamic array
        dynamicArray.RemoveAt(2)

        'Printing elements of dynamic array after removing an element
        output += "Printing Dynamic Array after removing an element" & Environment.NewLine
        For Each element As Integer In dynamicArray
            output += element & " "
        Next

        ' Displaying output in a listbox
        For Each line As String In output.Split(Environment.NewLine)
            If Not String.IsNullOrWhiteSpace(line) Then
                ListBox1.Items.Add(line)
            End If
        Next
    End Sub
End Class

Output:

dynamicarry

This code first initializes a dynamic array of integers and adds four elements to it. Then, it prints the elements of the array and removes an element from it. Finally, it prints the elements of the modified array.
The output of the code is stored in the output variable as a string. This string is then split into lines using the Environment.NewLine character as the delimiter. Each line is added to a listbox named ListBox1 using the Items.Add method.

Conclusion

In conclusion, VB.NET provides a variety of array types that can be used to store and manipulate data. Each array type has its own advantages and disadvantages, and choosing the right type of array for your application can have a significant impact on performance and memory usage. By understanding the different types of arrays and how to use them, you can write more efficient and effective VB.NET code.

Q: 1. What is an array in VB.NET?

A: An array is a collection of elements of the same data type that are stored in contiguous memory locations

Q: 2. What is the difference between a one-dimensional array and a multidimensional array?

A: A one-dimensional array has only one dimension, while a multidimensional array has two or more dimensions.

Q: 3. How do you declare a dynamic array in VB.NET?

A: You can declare a dynamic array in VB.NET using the ReDim keyword.

Q: 4. How do you resize a dynamic array in VB.NET?

A: You can resize a dynamic array in VB.NET using the ReDim keyword.

Q: 5. What is a jagged array in VB.NET?

A: A jagged array is an array of arrays, where each array can have a different size.

More Links

An array retains a consistent-size sequential assortment of elements sharing the same type. An array constitutes a group of values known as elements, which exhibit a logical interconnection with one another. An array serves as a linear data structure encompassing a compilation of data elements of identical type, stored within a continuous memory location. Array: Within an array, each element is stored consecutively.

Leave a Reply

Your email address will not be published. Required fields are marked *