Arrays and Indexers

for RuBoard

Arrays are another important data type in practical programming. In C# arrays are objects. They are a reference data type. They are based on the class System.Array and so inherit the properties and methods of this class. After examining one-dimensional arrays, we examine two higher-dimensional varieties. A "jagged" array is an array of arrays, and each row can have a different number of elements. In "rectangular" arrays, all rows have the same number of elements. Arrays are a special kind of collection, which means that the foreach loop can be used in C# for iterating through array elements.

We conclude the section with a discussion of indexers, which provides a way to access encapsulated data in a class with an array notation.

Arrays

An array is a collection of elements with the following characteristics.

  • All array elements must be of the same type. The element type of an array can be any type, including an array type. An array of arrays is often referred to as a jagged array.

  • An array may have one or more dimensions. For example, a two-dimensional array can be visualized as a table of values. The number of dimensions is known as the array's rank .

  • Array elements are accessed using one or more computed integer values, each known as an index . A one-dimensional array has one index.

  • In C# an array index starts at 0, as in other C family languages.

  • The elements of an array are created when the array object is created. The elements are automatically destroyed when there are no longer any references to the array object.

One-Dimensional Arrays

An array is declared using square brackets [] after the type, not after the variable.

 int [] a;                  // declares an array of int 

Note that the size of the array is not part of its type. The variable declared is a reference to the array.

You create the array elements and establish the size of the array using the new operator.

 a = new int[10];    // creates 10 array elements 

The new array elements start out with the appropriate default values for the type (0 for int ).

You may both declare and initialize array elements using curly brackets, as in C/C++.

 int a[] = {2, 3, 5, 7, 11}; 

You can indicate you are done with the array elements by assigning the array reference to null .

 a = null; 

The garbage collector is now free to deallocate the elements.

System.Array

Arrays are objects. System.Array is the abstract base class for all array types. Accordingly, you can use the properties and methods of System.Array for any array. Here are some examples:

  • Length is a property that returns the number of elements currently in the array.

  • Sort is a static method that will sort the elements of an array.

  • BinarySearch is a static method that will search for an element in a sorted array, using a binary search algorithm.

 int [] array = {5, 2, 11, 7, 3};  Array.Sort  (a);           // sorts the array  for (int i = 0; i <  a.Length  ; i++)      Console.Write("{0} ", a[i]);  Console.WriteLine();  int target = 5;  int index =  Array.BinarySearch  (a, target);  if (index < 0)      Console.WriteLine("{0} not found", target);  else      Console.WriteLine("{0} found at {1}", target, index); 

A complete program containing the code shown above can be found in ArrayMethods . Here is the output:

 2 3 5 7 11  5 found at 2 

Sample Program

The program ArrayDemo is an interactive test program for arrays. A small array is created initially, and you can create new arrays. You can populate an array either with a sequence of square numbers or with random numbers . You can sort the array, reverse the array, and perform a binary search (which assumes that the array is sorted in ascending order). You can destroy the array by assigning the array reference to null .

Interfaces for System.Array

If you look at the documentation for methods of System.Array , you will see many references to various interfaces, such as IComparable . By using such interfaces you can control the behavior of methods of System.Array . For example, if you want to sort an array of objects of a class that you define, you must implement the interface IComparable in your class so that the Sort method knows how to compare elements to carry out the sort. The .NET Framework provides an implementation of IComparable for all the primitive types. We will come back to this point after we discuss interfaces in Chapter 5.

Random-Number Generation

The ArrayDemo program contains the following code for populating an array with random integers between 0 and 100.

  Random rand = new Random();  for (int i = 0; i < size; i++)  {  array[i] = rand.Next(100);  } 

The .NET Framework provides a useful class, Random , in the System namespace that can be used for generating pseudorandom numbers for simulations.

Constructors

There are two constructors:

 Random();          // uses default seed  Random(int seed);  // seed is specified 

The default seed is based on date and time, resulting in a different stream of random numbers each time. By specifying a seed, you can produce a deterministic stream.

Next Methods

There are three overloaded Next methods that return a random int .

 int Next();  int Next(int maxValue);  int Next(int minValue, int maxValue); 

The first method returns an integer greater than or equal to zero and less than Int32.MaxValue . The second method returns an integer greater than or equal to zero and less than maxValue . The third method returns an integer greater than or equal to minValue and less than or equal to maxValue .

NextDouble Method

The NextDouble method produces a random double between 0 and 1.

 double NextDouble(); 

The return value r is in the range: 0 <= r < 1.

Jagged Arrays

You can declare an array of arrays, or a "jagged" array. Each row can have a different number of elements.

 int [][] binomial; 

You then create the array of rows, specifying how many rows there are (each row is itself an array).

 binomial = new int [rows][]; 

Next you create the individual rows.

 binomial[i] = new int [i+1]; 

Finally you can assign individual array elements.

 binomial[0][0] = 1; 

The example program Pascal creates and prints Pascal's triangle using a two-dimensional jagged array. Higher-dimensional jagged arrays can be created following the same principles.

Rectangular Arrays

C# also permits you to define rectangular arrays, where all rows have the same number of elements. First you declare the array.

 int [,] MultTable; 

Then you create all the array elements, specifying the number of rows and columns .

 MultTable = new int[rows, columns]; 

Finally you can assign individual array elements.

 MultTable[i,j] = i * j; 

The example program RectangularArray creates and prints out a multiplication table.

Higher-dimensional rectangular arrays can be created following the same principles.

Arrays as Collections

The class System.Array supports the IEnumerable interface. Hence arrays can be treated as collections , a topic we will discuss in Chapter 5. This means that a foreach loop can be used to iterate through the elements of an array.

The Pascal example code contains nested foreach loops to display the jagged array. The outer loop iterates through all the rows, and the inner loop iterates through all the elements within a row.

 // Pascal.cs  ...  Console.WriteLine(     "Pascal triangle via nested foreach loop");  foreach (int[] row in binomial)  {  foreach (int x in row)  {        Console.Write("{0} ", x);     }     Console.WriteLine();      } 

Indexers

C# provides various ways to help the user of a class access encapsulated data. Earlier in the chapter we saw how properties can provide access to a single piece of data associated with a class, making it appear like a public field. In this section we will see how indexers provide a similar capability for accessing a group of data items, using an array index notation. Indexers can be provided when there is a private array or other collection.

The program TestHotel\Step3 provides an illustration. This version of the Hotel class adds the capability to make hotel reservations , and the private array reservations stores a list of reservations in the form of ReservationListItem structure instances. The Hotel class provides the readonly property NumberReservations for the number of reservations in this list, and it provides a read-write indexer for access to the elements in this list. Note use of the keywords this and value in the indexer, which has a general syntax similar to that of properties.

 // Hotel.cs - Step 3  using System;  public struct ReservationListItem  {     public int CustomerId;     public int ReservationId;     public string HotelName;     public string City;     public DateTime ArrivalDate;     public DateTime DepartureDate;     public int NumberDays;  }  ...  public class Hotel  {     private string city;     private string name;     private int number;     private decimal rate;     private const int MAXDAY = 366;     private int[] numGuests;     private int nextReservation = 0;     private int nextReservationId = 1;     private const int MAXRESERVATIONS = 100;  private ReservationListItem[] reservations;  ...     public int NumberReservations     {        get        {           return nextReservation;        }     }  public ReservationListItem this[int index]   {   get   {   return reservations[index];   }   set   {   reservations[index] = value;   }   }  

The test program TestHotel.cs illustrates reading and writing individual array elements using the index notation.

 // Change the CustomerId of first reservation  ReservationListItem item = ritz[0];  item.CustomerId = 99;  ritz[0] = item;  ShowReservations(ritz); 
for RuBoard


Application Development Using C# and .NET
Application Development Using C# and .NET
ISBN: 013093383X
EAN: 2147483647
Year: 2001
Pages: 158

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