Arrays in Visual Basic .NET

In Visual Basic .NET, an array is a fixed-size sequential collection of elements of the same type. Arrays are useful in certain scenarios, although in typical VB.NET code, Lists or other collections are more common.

Imports System

Module ArrayExample
    Sub Main()
        ' Here we create an array 'a' that will hold exactly 5 Integers.
        ' The type of elements and length are both part of the array's declaration.
        ' By default, an array is zero-valued, which for Integers means 0s.
        Dim a(4) As Integer
        Console.WriteLine("emp: " & String.Join(", ", a))

        ' We can set a value at an index using the array(index) = value syntax,
        ' and get a value with array(index).
        a(4) = 100
        Console.WriteLine("set: " & String.Join(", ", a))
        Console.WriteLine("get: " & a(4))

        ' The Length property returns the length of an array.
        Console.WriteLine("len: " & a.Length)

        ' Use this syntax to declare and initialize an array in one line.
        Dim b() As Integer = {1, 2, 3, 4, 5}
        Console.WriteLine("dcl: " & String.Join(", ", b))

        ' In VB.NET, you can resize an array using ReDim, but it will reset all values
        ' unless you use the Preserve keyword.
        ReDim Preserve b(5)
        b(5) = 6
        Console.WriteLine("rsd: " & String.Join(", ", b))

        ' Array types are one-dimensional by default, but you can
        ' create multi-dimensional arrays.
        Dim twoD(1, 2) As Integer
        For i As Integer = 0 To 1
            For j As Integer = 0 To 2
                twoD(i, j) = i + j
            Next
        Next
        Console.WriteLine("2d: " & String.Join(", ", twoD.Cast(Of Integer)()))

        ' You can create and initialize multi-dimensional arrays at once too.
        Dim twoDInitialized = New Integer(,) {{1, 2, 3}, {4, 5, 6}}
        Console.WriteLine("2d: " & String.Join(", ", twoDInitialized.Cast(Of Integer)()))
    End Sub
End Module

Note that arrays appear in the form 1, 2, 3, ... when printed with Console.WriteLine and String.Join.

To run the program, save it as ArrayExample.vb and use the VB.NET compiler:

$ vbc ArrayExample.vb
$ mono ArrayExample.exe
emp: 0, 0, 0, 0, 0
set: 0, 0, 0, 0, 100
get: 100
len: 5
dcl: 1, 2, 3, 4, 5
rsd: 1, 2, 3, 4, 5, 6
2d: 0, 1, 2, 1, 2, 3
2d: 1, 2, 3, 4, 5, 6

This example demonstrates the basics of working with arrays in Visual Basic .NET. It covers creating arrays, setting and getting values, finding the length, and working with multi-dimensional arrays. The syntax and some concepts differ from other languages, but the fundamental idea of arrays as fixed-size collections remains the same.