Simple Arrays


If you need to use multiple objects of the same type, you can use an array. An array is a data structure that contains a number of elements of the same type.

Array Declaration

An array is declared by defining the type of the elements inside the array followed by empty brackets and a variable name; for example, an array containing integer elements is declared like this:

  int[] myArray; 

Array Initialization

After declaring an array, memory must be allocated to hold all the elements of the array. An array is a reference type, so memory on the heap must be allocated. This is done by initializing the variable of the array using the new operator with the type and the number of elements inside the array. Here you specify the size of the array.

Tip 

Value and reference types are covered in Chapter 3, “Objects and Types.”

  myArray = new int[4]; 

With this declaration and initialization, the variable myArray references four integer values that are allocated on the managed heap (see Figure 5-1).

image from book
Figure 5-1

Important 

The array cannot be resized after the size was specified without copying all elements. If you don’t know the number of elements that should be in the array in advance, you can use a collection. Collections are covered in Chapter 10, “Collections.”

Instead of using a separate line for the declaration and initialization, you can declare and initialize an array in a single line:

  int[] myArray = new int[4]; 

You can also assign values to every array element using an array initializer. Array initializers can only be used while declaring an array variable, not after the array is declared.

  int[] myArray = new int[4] {4, 7, 11, 2}; 

If you initialize the array using curly brackets, the size of the array can also be left out, as the compiler can count the number of elements itself:

  int[] myArray = new int[] {4, 7, 11, 2}; 

There’s even a shorter form using the C# compiler. Using curly brackets you can write the array declaration and initialization. The code generated from the compiler as the same as in the previous example.

  int[] myArray = {4, 7, 11, 2}; 

Accessing Array Elements

After an array is declared and initialized, you can access the array elements using an indexer. Arrays only support indexers that have integer parameters.

Tip 

With custom classes, you can also create indexers that support other types. You can read about creating custom indexers in Chapter 6, “Operators and Casts.

With the indexer, you pass the element number to access the array. The indexer always starts with a value of 0 for the first element. The highest number you can pass to the indexer is the number of elements minus one, since the index starts at zero. In the following example, the array myArray is declared and initialized with four integer values. The elements can be accessed with indexer values 0, 1, 2 and 3.

  int[] myArray = new int[] {4, 7, 11, 2}; int v1 = myArray[0];  // read first element int v2 = myArray[1];  // read second element myArray[3] = 44;      // change fourth element 

Important 

If you use a wrong indexer value where no element exists, an exception of type IndexOutOfRangeException is thrown.

If you don’t know the number of elements in the array, you can use the Length property that is used in this for statement:

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

Instead of using a for statement to iterate through all elements of the array, you can also use the foreach statement.

  foreach (int val in myArray) {    Console.WriteLine(val); } 

Tip 

The foreach statement makes use of the IEnumerable and IEnumerator interfaces that are discussed later in this chapter.

Using Reference Types

You cannot only declare arrays of predefined types; you can also declare arrays of a type of a custom class. Let’s start with this Person class with two constructors, the properties Firstname and Lastname, and an override of the ToString() method:

  public class Person {    public Person()    {    }    public Person(string firstname, string lastname)    {       this.firstname = firstname;       this.lastname = lastname;    }    private string firstname;    public string Firstname    {       get { return firstname; }       set { firstname = value; }    }    private string lastname;    public string Lastname    {       get { return lastname; }       set { lastname = value; }    }    public override string ToString()    {       return firstname + " " + lastname;    } } 

Declaring an array of two Person elements is similar to declaring an array of int:

  Person[] myPersons = new Person[2]; 

However, you must be aware that if the elements in the array are reference types, memory must be allocated for every array element. In case you use an item in the array where no memory was allocated, a NullReferenceException is thrown.

Tip 

Chapter 13, “Errors and Exceptions,” gives you all the information about errors and exceptions.

You can allocate every element of the array by using an indexer starting from 0:

  myPersons[0] = new Person("Ayrton", "Senna"); myPersons[1] = new Person("Michael", "Schumacher"); 

Figure 5-2 shows the objects in the managed heap with the Person array. myPersons is a variable that is stored on the stack. This variable references an array of Person elements that is stored on the managed heap. This array has enough space for two references. Every item in the array references a Person object that is also stored in the managed heap.

image from book
Figure 5-2

As you’ve seen it with the int type, you can also use an array initializer with custom types:

  Person[] myPersons = { new Person("Ayrton", "Senna"),                        new Person("Michael", "Schumacher") }; 




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

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