VB.NET String Array

String array

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. We can allocate the array and then assign into its memory locations separately.

Example

In this example, we create two string arrays. The first array is created with an initialization statement. You use curly brackets on the right side and can specify each string element.

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

Array

To continue, the second array uses the longer syntax. You must specify the capacity of the array in the Dim statement. Then, you can assign various elements into the memory you allocated.

Program that uses arrays: VB.NET

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
Note

In this example, there are a couple other aspects that bear examining. The For-Each loop construct is demonstrated. The iteration variable's type is specified with As, and the In keyword references the array variable.

Also:The Sub M in the program receives an array reference as its formal parameter. Similarly you can return an array from a Function.

Sort

Sorted letters: A to Z

One common task you must perform when using string arrays is sorting them. Typically, you will want an alphabetic (ASCII) sort. I have a useful article for accomplishing this in the VB.NET language. Please reference the linked article.

Sort Strings: Arrays and Lists

Summary

The VB.NET programming language

By using and comparing the two syntax patterns for VB.NET string arrays, we can determine which one to use in various program contexts. For simpler or smaller arrays, the initialization syntax shown in the first array is probably best.

Tip:For larger, sparsely filled or complex arrays, please consider using the imperative syntax alternative in the second array example.


VB.NET: String