108Microsoft Visual Studio 2010: A Beginner’s Guide

VB:

Sub ArrayDemo()

Dim stats(2) As Double

stats(0) = 1.1 stats(1) = 2.2 stats(2) = 3.3

Dim sum As Double = 0

For i As Integer = 0 To 2

sum += stats(i)

Next

Console.WriteLine( stats(0) & " + " & stats(1) & " + " & stats(2) & " = " & sum)

End Sub

In the C# example of Listing 4-7, you can see that the stats variable is declared as double[], an array of type double. You must instantiate arrays, as is done by assigning new double[3] to stats, where 3 is the number of elements in the array. C# arrays are accessed via a 0-based index, meaning that stats has three elements with indexes 0, 1, and 2.

The VB example declares stats as an array of type double. Notice that the rank of the array is 2, meaning that 2 is the highest index in the array. Since the array is 0-based, stats contains indexes 0, 1, and 2; three elements total.

Assigning values to an array means that you use the name of the array and specify the index of the element you want to assign a value to. For example, stats[0] (stats(0) in VB) is the first element of the stats array, and you can see from the listing how each element of the stats array is assigned the values 1.1, 2.2, and 3.3. The for loop adds each element of the array to the sum variable. Finally, you can see how to read values from an array by examining the argument to the Console.WriteLine statement. Using the element access syntax, you can see how to read a specific element from the stats array.

An array is a fixed-size collection, and therefore somewhat limited in functionality. In practice, you’ll want to use more sophisticated collections, like the List class, which is referred to as a generic collection. Not all collection classes in the .NET Framework are generic collections; however, generic collections are now the preferred kind of collection to use in most cases.

Page 131
Image 131
Microsoft 9GD00001 manual Microsoft Visual Studio 2010 a Beginner’s Guide