Example 1: Initialize


There is an easier way to initialize an array. We will add the Spanish words to illustrate. Notice that when you give a list you can not specify the size. Visual Basic will determine the size from the number of items in the list. The first item in the list is always (0) so we must include it:

Dim Months() As String = {"", "January", "February", "March",
   "April", "May", "June", "July", "August", 
   "September", "November", "December"}

Public Class Form1
    Dim English(10) As String 'global
    Dim Spanish As String() = {"cero", "uno", "dos", "tres", "cuatro", "cinco", _
   "seis", "siete", "ocho", "nueve", "diez"} 
   'Form Load is not shown here
    Private Sub Form1_MouseClick(ByVal sender As Object, ByVal e As _
      System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
        Dim MyBrush As New SolidBrush(Color.Black)
        Dim N As Integer
        For N = 0 To 10
            Me.CreateGraphics.DrawString(N, Me.Font, MyBrush, 0, N * 15)
            Me.CreateGraphics.DrawString(English(N), Me.Font, MyBrush, 15, N * 15)
            Me.CreateGraphics.DrawString(Spanish(N), Me.Font, MyBrush, 80, N * 15)
        Next N
    End Sub 'Form1_MouseClick
End Class
Experiment: Add column headings to the display. Declare English the same way that Spanish is declared and get rid of form load.

Next Page: Out of Bounds Exception

This lesson: Arrays in Visual Basic, Scalar Variables vs. Arrays, Example 1: Initialize, Out of Bounds Exception, Arrays of Objects, A lookup example, Julian Date, ReDim: Change the Size of the Array, No Duplicates, Collections