Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 107
Applying Arrays and Generics
Whatever code you write will typically need to group objects into a single collection of
that object type. For this, you can use an array, which is a container that can have zero or
many elements, each holding an instance of a particular type. You’ll soon see how to use
an array to locate the elements (items) you want. There are also generic collection classes
in the .NET Framework that are even more powerful than arrays. You’ll learn how to use
both arrays and generic collections in this section.
Coding Arrays
You’ve already seen several examples of arrays being used previously in this chapter. You
declare a variable of the array type, instantiate the array to a specified size, and then use
the array by indexing into its elements. Listing 4-7 shows an example that demonstrates
the mechanics of creating and using an array.
Listing 4-7 Creating and using an array
C#:
private void ArrayDemo()
{
double[] stats = new double[3];
stats[0] = 1.1;
stats[1] = 2.2;
stats[2] = 3.3;
double sum = 0;
for (int i = 0; i < stats.Length; i++)
{
sum += stats[i];
}
Console.WriteLine(
stats[0] + " + " +
stats[1] + " + " +
stats[2] + " = " +
sum);
}