Using Arrays

An array is simply a list or collection of items. Every array in the Common Language Runtime inherits from the System.Array class. Table 5.1 lists the terminology commonly used when talking about arrays.

Table 5.1. Array Terminology




An item stored in the array


The number of elements the array can hold


The number of dimensions of the array

Lower bound

The starting index for the array

In the following sections, you will learn how to create single-dimensional and multidimensional arrays. Then you will learn how to create and use a jagged array (array of arrays). Finally, you will learn how to pass an array as a parameter.

Understanding Single-Dimensional and Multidimensional Arrays

Single-dimensional and multidimensional arrays are exactly what their names imply. They have a rank of either 1 or N and take one of the following forms:

Single-Dimensional Array

 variable-type[] variableName = new variable-type[length] 

For multidimensional arrays, the form is only slightly different. You simply add a comma (,) in the declaration. One comma declares it as a two-dimensional array. Two commas declare it as a three-dimensional array, and so on.

Two-Dimensional Array

 variable-type[,] variableName = new variable-type[length, length] 

If you want to create an array using late binding, the static method System.Array.CreateInstance is the correct choice. The following code snippet declares and allocates an integer array of rank 1 and a length of 10; in other words, it declares a single-dimension array that can hold 10 integers:

 int[] intArray = new int[10]; 

In the preceding example, you will notice that the brackets ([]) are placed after the type and not after the variable. For those of you who come from a C++ background, this will be a hard thing to remember, but it makes sense and you will eventually get used to it. Also, even though System.Array provides a method named System.Array.GetLowerBounds that provides the lower bound of the array, arrays in C# have a zero-based index. The code in Listing 5.1 demonstrates how to create a single dimensional array of strings to hold the months of the year.

Listing 5.1. Storing the Months of the Year in a Single-Dimensional Array
 using System; namespace SimpleArrays {   class SimpleArray   {     static private string[] months =       new string[12] { "Jan", "Feb", "Mar", "Apr",         "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };     /// <summary>     /// The main entry point for the application.     /// </summary>     [STAThread]     static void Main(string[] args)     {       //       // TODO: Add code to start application here       //       foreach(string month in months)       {         System.Console.WriteLine(month);       }       System.Console.ReadLine();     }   } } 

Listing 5.2 presents the same array with a slight modification . The days in the month are added to the array. Also, to print out the contents of the array, the logic is changed to use a for loop instead of a foreach. In the following example, we know the exact lengths of the dimensions of the array. However, there are many instances when this information is not known. In such cases, you need to use the methods and properties provided by the System.Array class to determine these values:

 System.Array.GetLowerBound(int dimension) System.Array.GetUpperBound(int dimension) System.Array.Rank 

By adding the System.Array.GetUpperBound method call to the for loop, you can determine the length of the specified dimension and iterate through all items in that dimension.

Listing 5.2. Storing the Months of the Year Along with the Days in the Month in a Two-Dimensional Array
 using System; namespace TwoDimensionalArrayExample {   /// <summary>    /// Summary description for Class1.   /// </summary>   class SimpleArray   {     static private string[,] months =       new string[12,2]        { {"Jan", "31"}, {"Feb", "28"}, {"Mar", "31"},        {"Apr", "30"}, {"May", "31"}, {"Jun", "30"},        {"Jul", "31"}, {"Aug", "31"}, {"Sep", "30"},        {"Oct", "31"}, {"Nov", "30"}, {"Dec", "31"} };     /// <summary>     /// The main entry point for the application.     /// </summary>     [STAThread]     static void Main(string[] args)     {       for(int i=months.GetLowerBound(0); i<=months.GetUpperBound(0); i++)       {         System.Console.WriteLine(months[i, 0] + " has " + months[i, 1] + " days.");       }       System.Console.ReadLine();     }   } } 

Explaining Jagged Arrays

A jagged array is simply an array of arrays. It takes a little different form from that of a two-dimensional array in that the dimensions are no longer separated by a comma. Think of a standard two-dimensional array as rectangular and a jagged array as having an inconsistent shape, with each element of the array containing a different number of sub-elements. Now each dimension has its own set of brackets. The following code snippet demonstrates how to declare and initialize a jagged array of integers:

 int[][] intArray=new int[][] { new int[] {1,3,7,9},                                new int[] {2,4,6,8,10}                              } 

Listing 5.3 modifies the example introduced in the multidimensional array to use a jagged array instead of a two-dimensional array.

Listing 5.3. Jagged Array Example
 using System; namespace JaggedArrayExample {   class JaggedArray   {     static private string[][] months = new string[2][];     [STAThread]     static void Main(string[] args)     {       months[0] = new string[12]           {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",           "Oct", "Nov", "Dec"};       months[1] = new string[12]           {"31", "28", "31", "30", "31", "30", "31", "31", "30",            "31", "30", "31" };       for(int i=0; i<12; i++)       {         System.Console.WriteLine(months[0][i] + " has " + months[1][i] + " days.");       }       System.Console.ReadLine();     }   } } 

Passing Arrays as Parameters

Passing arrays as parameters can be accomplished in the same manner as all out and ref parameters. That is, all out parameters do not have to be initialized before calling the function to which you are calling. However, the function that you are calling must assign the array type before returning. In addition, all ref parameters must be assigned before calling the function. Listing 5.4 demonstrates the proper way to pass an Array using out and ref.

Listing 5.4. Passing Arrays as Parameters
 using System; namespace PassingArraysAsParameters {   class ArraysAsParameters   {     static public void InitializeArray(out string[][] months)     {       months = new string[2][];     }     static public void ModifyArray(ref string[][] months)     {       months[0] =         new string[12] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};       months[1] =         new string[12] { "31", "28", "31", "30", "31", "30", "31",           "31", "30", "31", "30", "31" };     }     [STAThread]     static void Main(string[] args)     {       string[][] months;       InitializeArray(out months);       ModifyArray(ref months);       for(int i=0; i<12; i++)       {         System.Console.WriteLine(months[0][i] + " has " + months[1][i] + " days.");       }       System.Console.ReadLine();     }   } } 

    Visual C#. NET 2003 Unleashed
    Visual C#. NET 2003 Unleashed
    ISBN: 672326760
    EAN: N/A
    Year: 2003
    Pages: 316 © 2008-2017.
    If you may any questions please contact us: