TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

VB.NET Array Examples: String Arrays

These VB.NET examples show arrays and string arrays. An array stores many elements of one type together.

Arrays. In an array, one element is stored after another in a linear way.

Arrays often provide the best performance for certain requirements.

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 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) = "deves"
	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... deves... 2014...

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

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

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

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.

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

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. 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, 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-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.

Length, LongLength. An array stores its element count. The Length property returns this count as an Integer. LongLength, useful for large arrays, returns a Long value.

Note: The length of every array is stored directly inside the array object. It is not computed when we access it. This makes it fast.

VB.NET that demonstrates Length property

Module Module1
    Sub Main()
	' Create an array of three strings.
	Dim array() As String = {"Dot", "Net", "Perls"}
	Console.WriteLine(array.Length)
	Console.WriteLine(array.LongLength)

	' Change the array to have two strings.
	array = {"OK", "Computer"}
	Console.WriteLine(array.Length)
	Console.WriteLine(array.LongLength)

	Console.ReadLine()
    End Sub
End Module

Output

3
3
2
2

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.

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

Two-dimensional. 2D arrays have complex syntax. We have data that should be stored in rows and columns. With a two-dimensional array, we store a rectangular collection of elements.

Here: This program populates a new 2D array. The (,) syntax is used to declare the array as a two-dimensional array.

And: For initializing the values, we use the String constructor and then the {} brackets to contain the element rows.

GetUpperBound: Returns how many elements are in a dimension (bound) of the array. For a 2D array, we can use the arguments 0 or 1.

VB.NET that uses 2D array

Module Module1
    Sub Main()
	' Declare two-dimensional array of strings.
	Dim values(,) As String =
	    New String(,) {{"ant", "aunt"},
			   {"Sam", "Samantha"},
			   {"clozapine", "quetiapine"},
			   {"flomax", "volmax"},
			   {"toradol", "tramadol"}}

	' Get bounds of the array.
	Dim bound0 As Integer = values.GetUpperBound(0)
	Dim bound1 As Integer = values.GetUpperBound(1)

	' Loop over all elements.
	For i As Integer = 0 To bound0
	    For x As Integer = 0 To bound1
		' Get element.
		Dim s1 As String = values(i, x)
		Console.Write(s1)
		Console.Write(" "c)
	    Next
	    Console.WriteLine()
	Next
    End Sub
End Module

Output

ant aunt
Sam Samantha
clozapine quetiapine
flomax volmax
toradol tramadol

Three-dimensional. Arrays sometimes have more than one or two dimensions. Three-dimensional arrays are rarely useful. But the syntax is easy to understand.

First: When you create a 3D array, please specify the dimensions of the array with the maximum indexes of each dimension.

Next: To assign elements within the multidimensional array we use three numbers separated by commas.

Tip: The argument to GetLength is the dimension index. GetLength returns an element count, not a maximum index of the dimension.

VB.NET that creates 3D array

Module Module1
    Sub Main()
	' Declare 3D array.
	' ... Specify maximum indexes of dimensions.
	Dim threeD(2, 4, 3) As Integer
	threeD(0, 0, 0) = 1
	threeD(0, 1, 0) = 2
	threeD(0, 2, 0) = 3
	threeD(0, 3, 0) = 4
	threeD(0, 4, 0) = 5
	threeD(1, 1, 1) = 2
	threeD(2, 2, 2) = 3
	threeD(2, 2, 3) = 4

	' Loop over three dimensions and display.
	For i As Integer = 0 To threeD.GetLength(2) - 1
	    For y As Integer = 0 To threeD.GetLength(1) - 1
		For x As Integer = 0 To threeD.GetLength(0) - 1
		    Console.Write(threeD(x, y, i))
		Next
		Console.WriteLine()
	    Next
	    Console.WriteLine()
	Next
    End Sub
End Module

Output

100
200
300
400
500

000
020
000
000
000

000
000
003
000
000

000
000
004
000
000

Jagged array. This kind of array is uneven in shape. It is an array of arrays. If the subarrays you need vary in length, a jagged array becomes extremely efficient.

First: This program uses the ()() syntax after the jagged array identifier to signify that the array contains other arrays.

Also: Temporary arrays are created in the standard way in VB.NET and then assigned to elements in the jagged array.

Finally: Two nested For-loops are used to loop through the top-level array and all the subarrays.

VB.NET that uses jagged array

Module Module1
    Sub Main()
	' Create jagged array with maximum index of 2.
	Dim jagged()() As Integer = New Integer(2)() {}

	' Create temporary array and place in index 0.
	Dim temp(2) As Integer
	temp(0) = 1
	temp(1) = 2
	temp(2) = 3
	jagged(0) = temp

	' Create small temporary array and place in index 1.
	Dim temp2(0) As Integer
	jagged(1) = temp2

	' Use array constructor and place result in index 2.
	jagged(2) = New Integer() {3, 4, 5, 6}

	' Loop through top-level arrays.
	For i As Integer = 0 To jagged.Length - 1

	    ' Loop through elements in subarrays.
	    Dim inner As Integer() = jagged(i)
	    For a As Integer = 0 To inner.Length - 1
		Console.Write(inner(a))
		Console.Write(" "c)
	    Next
	    Console.WriteLine()
	Next
    End Sub
End Module

Output

1 2 3
0
3 4 5 6

Jagged, performance. Jagged arrays can use less memory and be faster than two-dimensional arrays. If the shape of your data is uneven, they can save a lot of memory.

Info: Jagged arrays can be slower to allocate and construct than 2D arrays. They require multiple allocations.

But: They can use some optimizations meant for single-dimensional arrays that 2D arrays don't use. This can optimize lookups of elements.

2D array alternatives. There are some complexities involved in multidimensional arrays. They can cause excess memory usage. And this can negatively impact performance in programs.

Dictionary: In a Dictionary, we could use a string key containing the three numbers to store elements. This is not ideal, but could help.

Dictionary

List: For small amounts of data, we could use a List of Tuples (with coordinate items). Linear searches can locate elements.

ListTuple

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

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. 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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf