Arrays

 
Chapter 2 - C# Basics
bySimon Robinsonet al.
Wrox Press 2002
  

Arrays in C# differ substantially from arrays in both VB and C/C++, both in syntax and in the underlying implementation, although C# array syntax looks superficially similar to C++ syntax. As in C/C++ (and in Java), arrays in C# are indicated with square brackets.

In VB, arrays are actually SAFEARRAY variables . The use of a SAFEARRAY involves some overhead while making the arrays syntactically simpler to work with.

In C and C++, the name of an array is just a pointer to an address in memory, and the index to an array is simply an offset from that address. Although the C/C++ approach to arrays is flexible - you can do some fancy things with pointer arithmetic to move from element to element - it is also error-prone . Since C and C++ do not track the size of the arrays, there is nothing to stop a program from referencing an element outside the bounds of an array, possibly corrupting other data, and generating an error.

To overcome the shortcomings of C and C++, C# supports the array as a definite, distinct type. By treating arrays as objects with methods and properties (including ranges), the CLR is able to catch these kinds of out-of-bounds errors. Moreover, if an index-out-of-bounds error occurs during the course of a C# program, the CLR will throw a special type of error object that error handling routines can specifically respond to.

Array Syntax

C# takes such a different approach to arrays that it enforces a unique syntax for them. When you declare an array in C#, what is actually going on behind the scenes is that an instance of the .NET base class System.Array is being instantiated . C# array operations look to you like normal array code, but in fact the C# compiler translates your code into various method calls on System.Array . This gives the benefit of extra features compared to a plain C++-style array and even compared to a VB SAFEARRAY .

Arrays in C# are declared by fixing a set of square brackets to the end of the variable type of the individual elements (note that all the elements in an array must be of the same data type).

Important 

A note to VB users: arrays in C# use square brackets, not parentheses.

For example, while int represents a single integer, int[] represents an array of integers:

   int[] integers;   

To initialize the array with specific dimensions, we can use the new keyword, giving the size in the square brackets after the type name:

   // Create a new array of 32 ints     int[] integers = new int[32];   

If you hadn't already guessed, Array is a reference type (as are all classes). The use of the new keyword strongly hints at this fact. However, each individual array element is an int and therefore a value type.

To access an individual element within the array, we use the usual syntax, placing the index of the element in square brackets after the name of the array. All C# arrays use zero-based indexing, so we can reference the first variable with the index zero:

   integers[0] = 35;   

Accordingly, we reference the thirty-second element value with an index value of 31:

   integers[31] = 432;   

C#'s array syntax is flexible, too. In fact, C# allows us to declare arrays without initializing them, so that the array can be dynamically sized later in the program. With this technique, we are basically creating a null reference, and later pointing that reference at a dynamically allocated stretch of memory locations requested with the new keyword:

   int[] integers;     integers = new int[32];   

This syntax is certainly a lot easier than using malloc and sizeof . It is a lot less prone to memory leaks, too. In C or C++, a segment of memory referenced by an array will remain allocated on the heap unless specifically deallocated. In contrast, C# arrays, like other C# objects, are managed by the CLR and marked for automatic deallocation once they are no longer referenced.

One of the nice features of C and C++ arrays was the way that you could declare and initialize an array with a hard-coded list of initial values in curly braces. Thankfully, C# preserves this handy capability:

   string[] myArray = {"first element", "second element", "third element"};   

Note that it is perfectly permissible to use a variable to set how many elements the array will contain, like this:

   int len;     len = GetArraySize();   // assume this function works out how big we want     // the array to be     string[] myArray = new string[len];   

However you cannot change the size of an array once it has been instantiated (other than by copying the contents to a new array). If you want to dynamically add elements to an array, you will have to create an instance of the ArrayList object, which is in the System.Collections namespace. This is covered in detail in Chapter 5.

Obviously, you cannot assign more values to an array than there are elements.

Working with Arrays

Since arrays are represented by a specific type in C#, they have their own methods, for example to get the length of the array. This means that working with arrays in C# is very easy indeed.

For example, to find out the size of a one-dimensional array called integers , we can use the Length property:

   int arrayLength = integers.Length;   

If the array elements are of one of the predefined types, we can also sort the array into ascending order using the static Array.Sort() method:

   Array.Sort(myArray);   

Notice that we call this as a static method of the Array class, and not as a method of our array instance. We specify the array we want to sort by passing it in as a parameter to the method.

Sorting can alternatively be achieved using the System.Array.Sort() method and the IComparer interface.

Finally, we can reverse the existing order of the elements in an array using the static Reverse() method:

   Array.Reverse(myArray);   

The following short example stores a short list of famous artists ' names in a string array, sorts the array into reverse alphabetical order, and then loops through the array to display each name in order in the console window:

   string[] artists = {"Leonardo", "Monet", "Van Gogh", "Klee"};     Array.Sort(artists);     Array.Reverse(artists);     foreach (string name in artists)     {     Console.WriteLine(name);     }   

Multidimensional Arrays in C#

C# supports multidimensional arrays in two varieties. The first kind is the rectangular array. A two-dimensional rectangular array is one in which every row has the same number of columns . This is also known as a matrix . As demonstrated in the following example, rectangular arrays are relatively simple to declare and initialize. Here, we declare a two dimensional rectangular array of four rows, each of which has exactly two columns:

   string[,] beatleName = { {"Lennon","John"},     {"McCartney","Paul"},     {"Harrison","George"},     {"Starkey","Richard"} };   

Note that we use a comma to separate the dimensions in the array declaration, even though we don't actual specify the size of the dimensions. In order to declare a three-dimensional string array, we would use:

   string[,,] my3DArray;   

An alternative way of initializing the array would be to use nested for loops, like this:

   double [, ] matrix = new double[10, 10];     for (int i = 0; i < 10; i++)     {     for (int j=0; j < 10; j++)     matrix[i, j] = 4;     }   

If the array has more than one dimension, we can get the length of any specific dimension using the GetLength() method:

   // Get the length of the first dimension     int arrayLength = Integers.GetLength(0);   

The second kind of multidimensional array that C# supports is the orthogonal , or so-called jagged array. A jagged two-dimensional array is one in which every row can have a different number of columns. Although obviously more flexible than rectangular arrays, jagged arrays are, as you might guess, more difficult to instantiate and initialize. In creating a jagged array, we're basically creating an array of arrays:

   int[][] a = new int[3][];     a[0] = new int[4];     a[1] = new int[3];     a[2] = new int[1];   

Here, instead of using commas to indicate the number of dimensions in the array, we use an extra set of square brackets for each dimension. Therefore, to declare a three-dimensional jagged array of int s, we would use:

   int[][][] ints;   

Iterating through the elements in a jagged array requires more work than iterating through the elements in a rectangular array, too. As you loop through each row, you have to use the array's GetLength() method to dynamically ascertain the number of columns that you should loop through. The following example, AuthorNames , illustrates this point.

 using System; namespace Wrox.ProCSharp.Basics {    class MainEntryPoint    {       static void Main()       {   // Declare a two-dimension jagged array of authors' names     string[][] novelists = new string[3][];     novelists[0] = new string[] {     "Fyodor", "Mikhailovich", "Dostoyevsky"};     novelists[1] = new string[] {     "James", "Augustine", "Aloysius", "Joyce"};     novelists[2] = new string[] {     "Miguel", "de Cervantes", "Saavedra"};     // Loop through each novelist in the array     int i;     for (i = 0; i < novelists.GetLength(0); i++)     {     // Loop through each name for the novelist     int j;     for (j = 0; j < novelists[i].GetLength(0); j++)     {     // Display current part of name     Console.Write(novelists[i][j] + " ");     }     // Start a new line for the next novelist     Console.Write("\n");   }       }    } } 

Running this example gives the following result:

  csc AuthorNames.cs  Microsoft (R) Visual C# .NET Compiler version 7.00.9466 for Microsoft (R) .NET Framework version 1.0.3705 Copyright (C) Microsoft Corporation 2001. All rights reserved. AuthorNames Fyodor Mikhailovich Dostoyevsky James Augustine Aloysius Joyce Miguel de Cervantes Saavedra 
  


Professional C#. 2nd Edition
Performance Consulting: A Practical Guide for HR and Learning Professionals
ISBN: 1576754359
EAN: 2147483647
Year: 2002
Pages: 244

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