Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

278 Part II Programming Fundamentals


Declaring an Array and Assigning It Initial Values


It is also possible to declare an array and assign it initial values at the same time. This
statement syntax is somewhat parallel to what you learned about assigning an initial value to
a variable at the moment of declaration, and it is useful when you know in advance just how
large an array needs to be and what its contents are.

To create an array in this manner, you use what is called an array literal. An array literal consists of
a list of comma-separated values that are enclosed in braces ({}). When using this syntax, you can
either supply the array type or let Visual Basic use type inference to determine what type the array
should be. For example, to declare a one-dimensional array named Waiters of type String and fill
it with seven names, you would use the following syntax:

Dim Waiters() As String = {"Ben", "Sue", "Lee", "Kim", "Pat", "Eve", "Sal"}

Note that the size of this array is determined automatically by Visual Basic when Waiters is
declared. In addition, if you don’t indicate an array type, Visual Basic will use type inference
to determine the right array data type for you. Obviously if all the values are the same
type, it should be clear to the compiler what data type should be used for the array. But if
there is a mixture of types, such as an assortment of integer, single, and double-precision
numbers, Microsoft Visual Studio will pick a data type for the array that is large enough to
accommodate all the values. In many cases, this will be the data type Object because Object
variables (and arrays) are specifically designed to hold any type of data.

The following statement declares an array named Investments and uses an array literal to add
four values to the array when it is created. Since no type is specified, Visual Basic evaluates
the array elements and determines that in this case, the Object type is most appropriate.

Dim Investments() = {5000, 20350.50, 499.99, 10000}

Note If the compiler’s Option Infer setting is set to On, the Double type will be specified when
the above statement is executed. See Chapter 1 for help adjusting this setting.

A multi-dimensional array can also be declared in this way, although you need to take care
to list the elements in the proper order (that is, row 0 first, then row 1, row 2, and so on).
For example, the following statement declares a two-dimensional array named Rectangle
and assigns four values to the array:

Dim Rectangle = {{10, 20}, {50, 60}}

This array has two rows and two columns. Array element (0, 0—that is, row 0, column 0)
now contains a value of 10 and element (0, 1—that is, row 0, column 1) now contains
Free download pdf