Chapter 7: Arrays and Strings


This chapter returns to the subject of C#’s data types. It discusses arrays and the string type. The foreach loop is also examined.

Arrays

An array is a collection of variables of the same type that are referred to by a common name. In C#, arrays can have one or more dimensions, although the one-dimensional array is the most common. Arrays are used for a variety of purposes because they offer a convenient means of grouping together related variables. For example, you might use an array to hold a record of the daily high temperature for a month, a list of stock prices, or your collection of programming books.

The principal advantage of an array is that it organizes data in such a way that it can be easily manipulated. For example, if you have an array containing the dividends for a selected group of stocks, it is easy to compute the average income by cycling through the array. Also, arrays organize data in such a way that it can be easily sorted.

Although arrays in C# can be used just like arrays in other programming languages, they have one special attribute: they are implemented as objects. This fact is one reason that a discussion of arrays was deferred until objects had been introduced. By implementing arrays as objects, several important advantages are gained, not the least of which is that unused arrays can be garbage-collected.

One-Dimensional Arrays

A one-dimensional array is a list of related variables. Such lists are common in programming. For example, you might use a one-dimensional array to store the account numbers of the active users on a network. Another array might store the current batting averages for a baseball team.

To declare a one-dimensional array, you will use this general form:

 type[ ] array-name = new type[size];

Here, type declares the base type of the array. The base type determines the data type of each element that comprises the array. Notice the square brackets that follow type. They indicate that a one-dimensional array is being declared. The number of elements that the array will hold is determined by size. Since arrays are implemented as objects, the creation of an array is a two-step process. First, you declare an array reference variable. Second, you allocate memory for the array, assigning a reference to that memory to the array variable. Thus, arrays in C# are dynamically allocated using the new operator.

Note 

If you come from a C or C++ background, pay special attention to the way arrays are declared. Specifically, the square brackets follow the type name, not the array name.

Here is an example. The following creates an int array of ten elements and links it to an array reference variable named sample:

 int[] sample = new int[10];

This declaration works just like an object declaration. The sample variable holds a reference to the memory allocated by new. This memory is large enough to hold ten elements of type int.

As with objects, it is possible to break the preceding declaration in two. For example:

 int[] sample; sample = new int[10];

In this case, when sample is first created, it refers to no physical object. It is only after the second statement executes that sample is linked with an array.

An individual element within an array is accessed by use of an index. An index describes the position of an element within an array. In C#, all arrays have zero as the index of their first element. Because sample has ten elements, it has index values of 0 through 9. To index an array, specify the number of the element you want, surrounded by square brackets. Thus, the first element in sample is sample[0], and the last element is sample[9]. For example, the following program loads sample with the numbers 0 through 9:

 // Demonstrate a one-dimensional array. using System; class ArrayDemo {   public static void Main() {     int[] sample = new int[10];     int i;     for(i = 0; i < 10; i = i+1)       sample[i] = i;     for(i = 0; i < 10; i = i+1)       Console.WriteLine("sample[" + i + "]: " +                          sample[i]);   } }

The output from the program is shown here:

 sample[0]: 0 sample[1]: 1 sample[2]: 2 sample[3]: 3 sample[4]: 4 sample[5]: 5 sample[6]: 6 sample[7]: 7 sample[8]: 8 sample[9]: 9

Conceptually, the sample array looks like this:

image from book

Arrays are common in programming because they let you deal easily with large numbers of related variables. For example, the following program finds the average of the set of values stored in the nums array by cycling through the array using a for loop:

 // Compute the average of a set of values. using System; class Average {   public static void Main() {     int[] nums = new int[10];     int avg = 0;     nums[0] = 99;     nums[1] = 10;     nums[2] = 100;     nums[3] = 18;     nums[4] = 78;     nums[5] = 23;     nums[6] = 63;     nums[7] = 9;     nums[8] = 87;     nums[9] = 49;     for(int i=0; i < 10; i++)       avg = avg + nums[i];     avg = avg / 10;          Console.WriteLine("Average: " + avg);   } }

The output from the program is shown here:

 Average: 53

Initializing an Array

In the preceding program, the nums array was given values by hand, using ten separate assignment statements. While that is perfectly correct, there is an easier way to accomplish this. Arrays can be initialized when they are created. The general form for initializing a one-dimensional array is shown here:

 type[ ] array-name = { val1, val2, val3, ..., valN };

Here, the initial values are specified by val1 through valN. They are assigned in sequence, left to right, in index order. C# automatically allocates an array large enough to hold the initializers that you specify. There is no need to explicitly use the new operator. For example, here is a better way to write the Average program:

 // Compute the average of a set of values. using System; class Average {   public static void Main() {     int[] nums = { 99, 10, 100, 18, 78, 23,                    63, 9, 87, 49 };     int avg = 0;     for(int i=0; i < 10; i++)       avg = avg + nums[i];     avg = avg / 10;     Console.WriteLine("Average: " + avg);   } }

As a point of interest, although not needed, you can use new when initializing an array. For example, this is a proper, but redundant, way to initialize nums in the foregoing program:

 int[] nums = new int[] { 99, 10, 100, 18, 78, 23,                          63, 9, 87, 49 };

While redundant here, the new form of array initialization is useful when you are assigning a new array to an already-existent array reference variable. For example:

 int[] nums; nums = new int[] { 99, 10, 100, 18, 78, 23,                    63, 9, 87, 49 };

In this case, nums is declared in the first statement and initialized by the second.

One last point: It is permissible to explicitly specify the array size when initializing an array, but the size must agree with the number of initializers. For example, here is another way to initialize nums:

 int[] nums = new int[10] { 99, 10, 100, 18, 78, 23,                            63, 9, 87, 49 };

In this declaration, the size of nums is explicitly stated as 10.

Boundaries Are Enforced

Array boundaries are strictly enforced in C#; it is a runtime error to overrun or underrun the end of an array. If you want to confirm this for yourself, try the following program that purposely overruns an array:

 // Demonstrate an array overrun. using System; class ArrayErr {   public static void Main() {     int[] sample = new int[10];     int i;     // generate an array overrun     for(i = 0; i < 100; i = i+1)       sample[i] = i;   } }

As soon as i reaches 10, an IndexOutOfRangeException is generated and the program is terminated.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net