VB.NET: Array

VB.NET 2D Array

Two-dimensional: 2D

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. We examine a versatile way to use 2D arrays in the VB.NET language.

Based on:

.NET 4



This program populates a new 2D array. The (,) syntax is used to declare the array as a two-dimensional array. For initializing the values, we use the String constructor and then the {} brackets to contain the element rows.

VB.NET program 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(" "c)
    End Sub
End Module


ant aunt
Sam Samantha
clozapine quetiapine
flomax volmax
toradol tramadol

GetUpperBound. What does the GetUpperBound function do? It accesses the array and returns how many elements are in that dimension (bound) of the array. For a two-dimensional array, you can call GetUpperBound(0) and GetUpperBound(1).

Then:You can use the For-loop construct to access all elements in the two-dimensional array.

For Loops


The VB.NET programming language

We saw the basic syntax for using and initializing 2D arrays in the VB.NET language. We saw how to use the GetUpperBound function on a two-dimensional array and then how to loop through all elements.

Also:There are other important things to know about 2D arrays, but these examples introduce you to them.