Arrays in Visual Basic

If you change the for loop in the program to For N = 0 To 11 you will get a runtime exception when you click on the form:


Please note that it is the programmer's responsibility to make sure that the subscript is never less than 0 or more than the declared size. Doing so will result in an "Index Out of Range exception".

Declare and Initialize

There is an easier way to initialize an array. We will add the Spanish words to illustrate. Copy and paste this code to under the Dim English statment:

Dim Spanish As String() = {"cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"}

Replace the for loop with this one to show both English and Spanish in the list box:

For Num = 0 To 10
   S = Num & " " & English(Num) & " " & Spanish(Num)
   LstWords.Items.Add(S)
Next

Experiment: Rewrite the declaration for English to initialize with the values. Remove the statements in form load that assign values to English.

NEXT: Arrays of Objects