Learn to program in Visual Basic .NET, the right way

Collections - Arrays

What are Arrays?

Arrays are fixed collections used to store zero or more values that are the same data type.

Arrays have existed for a very long time. They were actually apart of a version of BASIC known as Dartmouth BASIC all the way back in 1966!

Fixed Length

Arrays are fixed length collections which means that they will contain a finite amount values.

Because arrays are fixed length, there is two methods of declaring an array.

The first method is to declare an array with a specified upper-bounds, this is to say I know how many values will be contained in the array and I will populate the values at a later time.

The second method is to intialize an array, this is to say I have an array and my values are already pre-loaded.

Example

The following demonstrates how to declare an array with an upper-bounds and assigning values in the array:

Fiddle: Live Demo

The following demonstrates how to initialize an array:

Fiddle: Live Demo

Get Values

You get a value from an array at a specified index.

Something important to consider is that arrays in Visual Basic .NET are zero based which is to say that the first item is at index '0'.

Example

The following demonstrates how to get values from an array:

Fiddle: Live Demo

Exception

If you try to get a value at either -1 or at an index that is greater than the upper-bounds of the array, then you will receive an IndexOutOfRangeException.

If you are unsure of if the index that you are using will be within the range of the array, then it is best to use a conditional statement to ensure that the index is within range.