VB.NET

.NET Array Class File String Sub ArrayList Cast Console DataTable DateTime Dictionary Enum For If IndexOf Interface Lambda LINQ List Nothing Parse Process Property Regex Replace Select Sort Split StringBuilder Substring

Array, simple

Arrays. In an array, one element is stored after another in a linear way. Arrays often provide the best performance for certain requirements.


Concept

Concepts. Other collections are built with internal arrays. There are many ways to initialize arrays. We can use Array class methods to change them.


String

String array. Here we create a four-element String array. We place four String references inside it. The strings are actually not stored in the array.

Instead:Reference values are stored in the array. And the objects are stored on the managed heap.

For Each:We use a For Each loop to iterate over the string elements within the array.

Based on:

.NET 4.5

VB.NET program that uses String array

Module Module1
    Sub Main()
	' Create array of maximum index 3.
	Dim array(3) As String
	array(0) = "dot"
	array(1) = "net"
	array(2) = "perls"
	array(3) = CStr(2014)

	' Display.
	For Each element As String In array
	    Console.Write(element)
	    Console.Write("... ")
	Next
    End Sub
End Module

Output

dot... net... perls... 2014...
Initializer

String array, initialization. A string array is created in various ways. In the VB.NET language we can create the array with all its data in an initialization statement.

Here:In this example, we create two string arrays. The first array is created with an initialization statement.

Note:In VB.NET syntax, you do not need to specify the size of the array on the left side.

Second:The next array uses the longer syntax. You must specify the capacity of the array in the Dim statement.

VB.NET program that uses arrays

Module Module1

    Sub Main()
	' Create an array with the simple initialization syntax.
	Dim array() As String = {"dog", "cat", "fish"}

	' Loop over the array.
	For Each value As String In array
	    Console.WriteLine(value)
	Next

	' Pass array as argument.
	M(array)

	' Create an array in several statements.
	' ... Use the maximum index in the declaration.
	' ... Begin indexing at zero.
	Dim array2(2) As String
	array2(0) = "bird"
	array2(1) = "dog"
	array2(2) = "gopher"

	' Loop.
	For Each value As String In array2
	    Console.WriteLine(value)
	Next

	' Pass as argument.
	M(array2)
    End Sub

    Sub M(ByRef array() As String)
	' Write length.
	Console.WriteLine(array.Length)
    End Sub

End Module

Output

dog
cat
fish
3
bird
dog
gopher
3
Program

Integer array. There are many syntax forms we use to declare 1D arrays. This example creates an array. It specifies the maximum index in the first statement.

Note:We must specify the maximum index, not the actual array element count or length.

VB.NET program that uses array

Module Module1
    Sub Main()
	' Create an array.
	Dim array(2) As Integer
	array(0) = 100
	array(1) = 10
	array(2) = 1

	For Each element As Integer In array
	    Console.WriteLine(element)
	Next
    End Sub
End Module

Output

100
10
1
Steps

Integer array. Often you can initialize an array in a simpler way than in the previous example. Here, we use the curly-bracket { } syntax to create an array of three elements.

VB.NET program that uses another array syntax form

Module Module1
    Sub Main()
	' Create array of three integers.
	Dim array() As Integer = {10, 30, 50}

	For Each element As Integer In array
	    Console.WriteLine(element)
	Next
    End Sub
End Module

Output

10
30
50
Program

For-loop, Length. We can use the For-loop construct. This allows us to access the index of each element. This is useful for additional computations or logic.

Length

Also:Using the For-loop syntax is better for when you need to modify elements within the array.

VB.NET program that uses For loop on array

Module Module1
    Sub Main()
	' New array of integers.
	Dim array() As Integer = {100, 300, 500}

	' Use for-loop.
	For i As Integer = 0 To array.Length - 1
	    Console.WriteLine(array(i))
	Next
    End Sub
End Module

Output

100
300
500
Pass

Array argument. We can pass an array to a subroutine or function. Please note that the entire array is not copied. Just a reference to the array is copied.

VB.NET program that passes array as argument

Module Module1
    Sub Main()
	Dim array() As Integer = {5, 10, 20}
	' Pass array as argument.
	Console.WriteLine(Example(array))
    End Sub

    ''' <summary>
    ''' Receive array parameter.
    ''' </summary>
    Function Example(ByVal array() As Integer) As Integer
	Return array(0) + 10
    End Function
End Module

Output

15
Return keyword

Return. We can return an array. This program shows the correct syntax. The Example function creates a two-element array and then returns it.

Then:The Main subroutine displays all its results by calling String.Join on them.

Join
VB.NET that returns array

Module Module1
    Sub Main()
	Console.WriteLine(String.Join(",", Example()))
    End Sub

    ''' <summary>
    ''' Return array.
    ''' </summary>
    Function Example() As String()
	Dim array(1) As String
	array(0) = "Perl"
	array(1) = "Python"
	Return array
    End Function
End Module

Output

Perl,Python
First

First, last. We get the first element with the index 0.
For the last element,
we take the array Length
and subtract one. This works on all non-empty, non-Nothing arrays.

Caution:Arrays that are Nothing will cause a NullReferenceException to occur if you access elements on them.

Nothing

Also:An empty array (one with zero elements) has no first or last element, so this code also will fail.

ToCharArray:In the example, we use the ToCharArray Function to convert a String "abc" into an array of three Chars.

ToCharArray
VB.NET that gets first, last elements

Module Module1
    Sub Main()
	' Get char array of three letters.
	Dim values() As Char = "abc".ToCharArray()

	' Get first and last chars.
	Dim first As Char = values(0)
	Dim last As Char = values(values.Length - 1)

	' Display results.
	Console.WriteLine(first)
	Console.WriteLine(last)
    End Sub
End Module

Output

a
c
If

If-test. Often we must check that an index is valid—that it exists within the array. We can use an If-statement. Here I check that the index 2 is less than the length (which is 3).

If Then

So:The index 2 can be safely accessed. But the index 50, tried next, causes an IndexOutOfRangeException.

VB.NET that checks index

Module Module1
    Sub Main()
	Dim values() As Integer = {5, 10, 15}

	' Check that index is a valid position in array.
	If 2 < values.Length Then
	    Console.WriteLine(values(2))
	End If

	' This causes an exception!
	Dim value = values(50)
    End Sub
End Module

Output

15

Unhandled Exception: System.IndexOutOfRangeException:
Index was outside the bounds of the array.
Sub

Subs. We search arrays with Find. We can copy and resize arrays with helpful subs. The Array.Reverse subroutine reverses the ordering of elements.

Array.CopyArray.FindArray.IndexOfArray.ResizeArray.Reverse

Tip:With arrays, using built-in subs is usually best. Writing custom methods should be avoided unless needed.


Copy: new object copied

Types. You must specify a type for every array element. Char arrays are useful for character-level manipulations. An Object array is useful for storing derived types with base references.

Byte ArrayChar ArrayObject Array
2D array

Dimensions. Arrays are not limited to one dimension. You can use two-dimensional arrays—arrays that are square or rectangular. You can even use jagged arrays.

2D Array3D ArrayJagged Array
Convert

Convert. We can convert types like an ArrayList into an array. Often built-in methods, like ToArray are available. We should use them when possible.

Convert ArrayList, ArrayConvert List, Array
The VB.NET programming language

Choose. VB.NET has global functions that have interesting effects. One example is the Choose function. This returns a specific element in an array.

Choose
Sort: ordering elements from A to Z, alphabetically

Sort. One common task you must perform when using string arrays is sorting them. Typically, you will want an alphabetic (ASCII) sort.

Sort

A review. Arrays are an important type.
They are used inside other types,
such as List
and Dictionary,
to implement those types' storage. They are often faster.