8.2 Arrays

An array is a group of variables—called elements—containing values of the same type. Arrays are reference types—an array variable is actually a reference to an array object. An array’s elements can be either value types or reference types, including other arrays—e.g., every element of an int array is an int value, and every element of a string array is a reference to a string object. Array names follow the same conventions as other variable names.

Logical Representation of an Array; Array-Access Expressions

Figure 8.1 shows a logical representation of an integer array called c that contains 12 elements. An app refers to any one of these elements with an array-access expression that includes the name of the reference to the array, c, followed by the index (i.e., position number) of the particular element in square brackets ([]). The first element in every array has index zero (0) and is sometimes called the zeroth element. Thus, the names of array c’s elements are c[0], c[1], c[2] and so on. The highest index in array c is 11—one less than the array’s number of elements, because indices begin at 0.

Fig. 8.1 A 12-element array.

Indices Must Be Nonnegative Integer Values

An index must be a nonnegative integer or integer expression with a value of type int, uint, long or ulong—or a value of a type that can be implicitly promoted to one of these types (as discussed in Section 7.6.1). If we assume that variable a is 5 and variable b is 6, then the statement


c[a + b] += 2;

evaluates the expression a + b to determine the index and in this case adds 2 to element c[11]. Array-access expressions can be used on the left side of an assignment to place a new value into an array element.

Examining Array c in More Detail

Let’s examine array c in Fig. 8.1 more closely. The name of the variable that references the array is c. Every array instance knows its own length and provides access to this information with the Length property. For example, the expression c.Length returns array c’s length (that is, 12). The Length property of an array is read only, so it cannot be changed. The array’s 12 elements are referred to as c[0], c[1], c[2], …, c[11]. Referring to elements outside of this range, such as c[-1] or c[12], is a runtime error (as we’ll demonstrate in Fig. 8.9). The value of c[0] is -45, the value of c[1] is 6, the value of c[2] is 0, the value of c[7] is 62 and the value of c[11] is 78. To calculate the sum of the values contained in the first three elements of array c and store the result in variable sum, we’d write


sum = c[0] + c[1] + c[2];

To divide the value of c[6] by 2 and assign the result to the variable x, we’d write


x = c[6] / 2;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset