2. Creating and Using Arrays

Like a List, an Array is a numbered list of items. Arrays are different from Lists in one important respect. When you create an List, it is initially empty, and you must call the Add() method to add slots. When you create an array, you specify the number of slots you want it to have. The number of slots is fixed; Arrays cannot expand or contract like Lists.

The items in an array are often referred to as the elements of the array. In C#, the elements in an array are always numbered starting from zero. That is, the index of the first element in the array is zero. If the length of the array is N, then the index of the last element in the array is N-1. The type of the individual items in an array is called the element type of the array.

Let's look at an example. The following statement creates an array of integers with 5 slots:

int[] list = new int[5];

The slots are numbered 0 to 4. To accomplish the same thing with an List, we would have had to call Add() five times after creating the List.

Let's examine this statement more closely. It has two parts:

The newly created array of integers is automatically filled with zeros. In C#, a newly created array is always filled with a known, default value: zero for numbers, false for boolean, the character with Unicode number zero for char, and null for objects.

The elements in the array, list, are referred to as list[0], list[1], list[2], list[3], and list[4]. The following loop would print all the integers in the array, list, to standard output:

        for (int i = 0; i < list.Length; i++) {
           Console.WriteLine( list[i] );
        }

Note the use of list.Length in the loop condition. Array variables have a Length property, which is similar to the Count property of Lists -- it returns the number of elements in the array.

We can put an item into the first slot like this:

list[0] = -99;

Later, we could use the value at index 0 in a calculation:

int count = list[0] * 2;

Note that array variables, such as list, hold a reference to an array. You can define an array variable without initializing it like this:

int[] list;

This variable is capable of referring to an array of ints, but initially its value is null (if it is a member variable in a class) or undefined (if it is a local variable in a method).

Every use of a variable in a program specifies a memory location. Think for a moment about what the computer does when it encounters a reference to an array element, list[k], while it is executing a program. The computer must determine which memory location is being referred to. To the computer, list[k] means something like this: "Get the pointer that is stored in the variable, list. Follow this pointer to find an array object. Get the value of k. Go to the k-th position in the array, and that's the memory location you want." There are two things that can go wrong here. Suppose that the value of list is null. If that is the case, then list doesn't even refer to an array. The attempt to refer to an element of an array that doesn't exist is an error. This is an example of a "null pointer" error. The second possible error occurs if list does refer to an array, but the value of k is outside the legal range of indices for that array. This will happen if k < 0 or if k >= list.Length. This is called an "array index out of bounds" error. When you use arrays in a program, you should be mindful that both types of errors are possible. However, array index out of bounds errors are by far the most common error when working with arrays.

For an array variable, just as for any variable, you can declare the variable and initialize it in a single step. For example,

int[] list = new int[5];

The new array is filled with the default value appropriate for the element type of the array -- zero for int and null for class types, for example. However, C# also provides a way to initialize an array variable with a new array filled with a specified list of values. In a declaration statement that creates a new array, this is done with an array initializer. For example,

int[] list = { 1, 4, 9, 16, 25, 36, 49 };

creates a new array containing the seven values 1, 4, 9, 16, 25, 36, and 49, and sets list to refer to that new array. The value of list[0] will be 1, the value of list[1] will be 4, and so forth. The length of list is seven, since seven values are provided in the initializer.

An array initializer takes the form of a list of values, separated by commas and enclosed between braces. The length of the array does not have to be specified, because it is implicit in the list of values. The items in an array initializer don't have to be constants. They can be variables or arbitrary expressions, provided that their values are of the appropriate type. For example, the following declaration creates an array of eight Colors. Some of the colors are given by expressions of the form "new Color(r,g,b)":

Color[] palette = { Color.black, Color.red, Color.pink, new Color(0,180,0), // dark green 
                    Color.green, Color.blue, new Color(180,180,255), // light blue 
                    Color.white };

A list initializer of this form can be used only in a declaration statement, to give an initial value to a newly declared array variable. It cannot be used in an assignment statement to assign a value to a variable that has been previously declared. However, there is another, similar notation for creating a new array that can be used in an assignment statement or passed as a parameter to a method. The notation uses another form of the new operator to create and initialize a new array object. For example to assign a new value to an array variable, list, that was declared previously, you could use:

list = new int[] { 1, 8, 27, 64, 125, 216, 343 };

The general syntax for this form of the new operator is

new base-type [ ] { list-of-values }

This is an expression whose value is an array object. It can be used in any context where an object of type base-type[] is expected. For example, if makeButtons is a method that takes an array of strings as a parameter, you could say:

           makeButtons( new string[] { "Stop", "Go", "Next", "Previous" } );