Arrays in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes how to declare and use arrays in Visual Basic .NET

Whenever you need to hold a list of similar or related data you use an array. Arrays can only hold a single data type.

To declare an array you use parentheses and unlike the standard variable it can hold more than one value.

For example, the following code declares an one-dimensional array of Strings named days with seven elements:

Dim days(6) As String 
' arrays are zero-based (the numbering in an array starts at zero)

To initialize an array you place the values inside curly braces separated by commas. The following code initializes a one-dimensional array of Strings:

                        ' Like this:                   
                        Dim days(6) As String = _
                        { "Sunday", "Monday", "Tuesday", "Wednesday", _
                         "Thursday", "Friday", "Saturday" }

                        ' Or like this:

                        ' Declare the array
                        Dim days(6) As String

                        ' Populate the array
                        days(0) = "Sunday"
                        days(1) = "Monday"
                        days(2) = "Tuesday"
                        days(3) = "Wednesday"
                        days(4) = "Thursday"
                        days(5) = "Friday"
                        days(6) = "Saturday"

To access individual element in the array you do it by providing an index value between 0 and a maximum possible value (total size of the array less 1) e.g.

                        Dim days(6) As String = _
                        { "Sunday", "Monday", "Tuesday", "Wednesday", _
                         "Thursday", "Friday", "Saturday" }
                        Console.WriteLine(days(0)) ' = Sunday               

Previous Lesson | Next Lesson

Share This

Home | About | Contact | Privacy Policy

Copyright 2018 - All Rights Reserved.